c# - System.ValueTuple 和 System.Tuple 有什么区别?

标签 c# .net tuples c#-7.0

我反编译了一些 C# 7 库,看到使用了 ValueTuple 泛型。什么是 ValueTuples,为什么不用 Tuple

最佳答案

What are ValueTuples and why not Tuple instead?

A ValueTuple 是一个反射(reflect)元组的结构,与原始 System.Tuple 相同类。

Tuple 之间的主要区别和 ValueTuple是:

  • System.ValueTuple是值类型(结构),而 System.Tuple是引用类型 ( class )。这在谈论分配和 GC 压力时很有意义。
  • System.ValueTuple不只是一个 struct ,它是一个可变的,因此在使用它们时必须小心。想想当一个类(class)持有 System.ValueTuple 时会发生什么作为一个领域。
  • System.ValueTuple通过字段而不是属性公开其项目。

在 C# 7 之前,使用元组不是很方便。它们的字段名称是 Item1 , Item2等,并且该语言没有像大多数其他语言(Python、Scala)那样为它们提供语法糖。

当 .NET 语言设计团队决定合并元组并在语言级别向它们添加语法糖时,一个重要因素是性能。与 ValueTuple作为值类型,您可以在使用它们时避免 GC 压力,因为(作为实现细节)它们将分配在堆栈上。

此外,一个 struct通过运行时获取自动(浅层)相等语义,其中 class没有。尽管设计团队确保元组的相等性会更加优化,因此为其实现了自定义相等性。

这是来自 design notes of Tuples 的一段话:

Struct or Class:

As mentioned, I propose to make tuple types structs rather than classes, so that no allocation penalty is associated with them. They should be as lightweight as possible.

Arguably, structs can end up being more costly, because assignment copies a bigger value. So if they are assigned a lot more than they are created, then structs would be a bad choice.

In their very motivation, though, tuples are ephemeral. You would use them when the parts are more important than the whole. So the common pattern would be to construct, return and immediately deconstruct them. In this situation structs are clearly preferable.

Structs also have a number of other benefits, which will become obvious in the following.


例子:

您可以很容易地看到使用 System.Tuple很快变得暧昧。例如,假设我们有一个计算 List<Int> 的总和和计数的方法。 :

public Tuple<int, int> DoStuff(IEnumerable<int> values)
{
    var sum = 0;
    var count = 0;
    
    foreach (var value in values) { sum += value; count++; }
   
    return new Tuple(sum, count);
}

在接收端,我们最终得到:

Tuple<int, int> result = DoStuff(Enumerable.Range(0, 10));

// What is Item1 and what is Item2?
// Which one is the sum and which is the count?
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);

将值元组解构为命名参数的方式是该功能的真正威力:

public (int sum, int count) DoStuff(IEnumerable<int> values) 
{
    var res = (sum: 0, count: 0);
    foreach (var value in values) { res.sum += value; res.count++; }
    return res;
}

在接收端:

var result = DoStuff(Enumerable.Range(0, 10));
Console.WriteLine($"Sum: {result.sum}, Count: {result.count}");

或者:

var (sum, count) = DoStuff(Enumerable.Range(0, 10));
Console.WriteLine($"Sum: {sum}, Count: {count}");

编译器好东西:

如果我们深入了解前面的示例,我们可以准确地看到编译器是如何解释 ValueTuple 的。当我们要求它解构时:

[return: TupleElementNames(new string[] {
    "sum",
    "count"
})]
public ValueTuple<int, int> DoStuff(IEnumerable<int> values)
{
    ValueTuple<int, int> result;
    result..ctor(0, 0);
    foreach (int current in values)
    {
        result.Item1 += current;
        result.Item2++;
    }
    return result;
}

public void Foo()
{
    ValueTuple<int, int> expr_0E = this.DoStuff(Enumerable.Range(0, 10));
    int item = expr_0E.Item1;
    int arg_1A_0 = expr_0E.Item2;
}

在内部,编译后的代码利用了 Item1Item2 ,但是所有这些都从我们这里抽象出来,因为我们使用的是分解的元组。带有命名参数的元组被注释为 TupleElementNamesAttribute .如果我们使用单个新变量而不是分解,我们会得到:

public void Foo()
{
    ValueTuple<int, int> valueTuple = this.DoStuff(Enumerable.Range(0, 10));
    Console.WriteLine(string.Format("Sum: {0}, Count: {1})", valueTuple.Item1, valueTuple.Item2));
}

请注意,当我们调试我们的应用程序时,编译器仍然需要(通过属性)使一些魔法发生,因为看到 Item1 会很奇怪。 , Item2 .

关于c# - System.ValueTuple 和 System.Tuple 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41084411/

相关文章:

c++ - 如何将元组扩展为可变参数模板函数的参数?

c# - MVC3 Controller 如何检索 HTTPPOST 参数?

javascript - JQuery 自动完成 - 简单的母版页问题

.net - 将 Observable<Timestamp<T>> 转换为 Observable<Time Interval<T>>

python - 如何比较同一元组列表中的出现次数

c++ - std::tuple 与 std::array 作为 std::vector 的项目

c# - 获得 Guid.NewGuid () 副本的机会有多大?

c# - 用于电子邮件发送的波兰字符 MIME 格式的问题

.net - 如何在配置 Jenkins 作业时排除/忽略项目(Dot Net)

c# - 无法在运行时找到静态资源,即使设计师可以看到它