📜  C#中的ValueTuple结构

📅  最后修改于: 2021-05-30 01:25:22             🧑  作者: Mango

在C#中,ValueTuple结构提供了用于创建值元组的静态方法。它在系统名称空间下定义。它是在.NET Framework 4.7中引入的,它在C#中提供了运行时实现元组。 ValueTuple结构用于表示不包含任何元素的元组。通常,它提供用于创建或比较值元组的静态方法。借助于ValueTuple结构的Create方法,您可以创建一个值元组,其中包含从0到8的元素。在以下方面,它与Tuple类不同:

  • 它是值类型而不是引用类型。
  • 它是可变的,而不是只读的。
  • 在ValueTuple中, item1item2item3等数据成员是字段而不是属性。

此结构实现IStructuralComparableIStructuralEquatableIComparableIComparable IEquatable ITuple接口。

方法

Method Description
CompareTo(ValueTuple) Compares the current ValueTuple instance to a specified ValueTuple instance.
Create() Creates a new value tuple with zero components.
Create(T1, T2, T3, T4, T5, T6, T7, T8) Creates a new value tuple with 8 components (an octuple).
Create(T1, T2, T3, T4, T5, T6, T7) Creates a new value tuple with 7 components (a septuple).
Create(T1, T2, T3, T4, T5, T6) Creates a new value tuple with 6 components (a sexuple).
Create(T1, T2, T3, T4, T5) Creates a new value tuple with 5 components (a quintuple).
Create(T1, T2, T3, T4) Creates a new value tuple with 4 components (a quadruple).
Create(T1, T2, T3) Creates a new value tuple with 3 components (a triple).
Create(T1, T2) Creates a new value tuple with 2 components (a pair).
Create(T1) Creates a new value tuple with 1 component (a singleton).
Equals(ValueTuple) Determines whether two ValueTuple instances are equal. This method always returns true.
Equals(Object) Returns a value that indicates whether the current ValueTuple instance is equal to a specified object.
GetHashCode() Returns the hash code for the current ValueTuple instance.
ToString() Returns the string representation of this ValueTuple instance.

例子:

// C# program to illustrate the 
// methods of ValueTuple struct
using System;
  
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating a value tuple with 
        // zero element using Create method
        var MyTple1 = ValueTuple.Create();
  
        // Using GetHashCode method
        Console.WriteLine("HashCode of a value tuple with "+
                 "zero elements: " + MyTple1.GetHashCode());
  
        // Creating a value tuple 
        var MyTple2 = ValueTuple.Create(56, 3);
        var MyTple3 = ValueTuple.Create(56, 45);
  
        // Using CompareTo method
        int res1 = MyTple2.CompareTo(MyTple3);
          
        // Display result
        Console.WriteLine("CompareTo Method Result: " + res1);
    }
}

输出:

HashCode of a value tuple with zero elements: 0
CompareTo Method Result: -1

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.valuetuple?view=netframework-4.8