C# 组元Tuple

来源:互联网 发布:国内人脸数据库 编辑:程序博客网 时间:2024/06/07 17:24


http://blog.csdn.net/aoshilang2249/article/details/40053213


组元是C# 4.0引入的一个新特性.需要基于.NET Framework 4.0或者更高版本。组元使用泛型来简化一个类的定义。组元多用于

方法的返回值,如果一个函数返回多个类型,这样就不在用out\ref等输出参数了,可以直接定义一个Tuple类型就可以了。


1.0 简单使用


[csharp] view plain copy print?
  1. //一个成员  
  2. Tuple<int> test = new Tuple<int>(1);  
  3. Console.WriteLine(test.Item1);  
  4.   
  5. //两个成员  
  6. Tuple<intdouble> test1 = new Tuple<intdouble>(2, 2.3);  
  7. Console.WriteLine(test1.Item1 + test1.Item2);  


2.0 嵌套使用


Tuple最多支持8个成员,如果多于8个就需要进行嵌套。

注意第8个成员很特殊,第8个成员必须嵌套定义成Tuple类型


[csharp] view plain copy print?
  1. //非8个元素  
  2. Tuple<int, Tuple<string>> test2 = new Tuple<int, Tuple<string>>(3, new Tuple<string>("Nesting"));  
  3. Console.WriteLine(test2.Item1);  
  4. Console.WriteLine(test2.Item2);  
  5. //8个元素  
  6. Tuple<intlongfloatdoubleshortbytechar, Tuple<int>> test3 =  
  7.     new Tuple<intlongfloatdoubleshortbytechar, Tuple<int>>(1,   
  8.         2, 3.0f, 4, 5, 6, 'h'new Tuple<int>(8));  
  9. Console.WriteLine(test3.Item1 + test3.Rest.Item1);  

原创粉丝点击