C#元组 TupleT1类用法介绍

2021年5月7日13:57:33 发表评论 695 次浏览

Tuple <T1>类用于创建1-tuple或singleton, 其中仅包含一个元素。你可以通过调用以下任一实例化Tuple <T1>对象Tuple <T1>构造函数 或由静态元组创建方法。你可以使用只读检索元组的单个元素的值项目1实例属性。

重要事项:

  • 它实现结构可比, 结构平等和可比接口。
  • 它在系统名称空间下定义。
  • 它表示将多个数据合并为一个数据集。
  • 它使我们能够创建, 操作和访问数据集。
  • 它从一个方法返回多个值, 而不使用out参数。
  • 它允许在单个参数的帮助下将多个值传递给方法。
  • 它还可以存储重复的元素。

建设者

建设者 描述
元组<T1>(T1) 初始化Tuple <T1>类的新实例。

属性

属性 描述
项目1 获取Tuple <T1>对象的单个元素的值。

例子:

//C# program to illustrate the constructor 
//and property of class Tuple<T1>
using System;
  
class GFG {
  
     //Main method
     static public void Main()
     {
  
         //Creating 1-Tuple
         //Using Tuple<T1>(T1)
         Tuple<int> mytuple = new Tuple<int>(22);
  
         //Accessing the values
         Console.WriteLine( "Value of the Element is: " + mytuple.Item1);
     }
}

输出如下:

Value of the Element is: 22

方法

方法 描述
等于(对象) 返回一个值, 该值指示当前的Tuple <T1>对象是否等于指定的对象。
GetHashCode() 返回当前Tuple <T1>对象的哈希码。
GetType() 获取当前实例的类型。
MemberwiseClone() 创建当前对象的浅表副本。
ToString() 返回表示此Tuple <T1>实例的值的字符串。

例子:

//C# program to determine the 
//given tuples are equal or not
using System;
  
class GFG {
  
     //Main method
     static public void Main()
     {
  
         //Creating 1-Tuple
         //Using Tuple<T1>(T1)
         Tuple<int> mytuple1 = new Tuple<int>(22);
         Tuple<int> mytuple2 = new Tuple<int>(22);
  
         //Using Equals method
         if (mytuple1.Equals(mytuple2))
         {
             Console.WriteLine( "Tuple Matched.." );
         }
  
         else
         {
             Console.WriteLine( "Tuple not matched.." );
         }
     }
}

输出如下:

Tuple Matched..

参考:

  • https://docs.microsoft.com/en-us/dotnet/api/system.tuple-1?view=netframework-4.8

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: