c#组元(Tuple)的使用

组元(Tuple)是C# 4.0引入的一个新特性,可以在.NET Framework 4.0或更高版本中使用。组元使用泛型来简化类的定义,多用于方法的返回值。在函数需要返回多个类型的时候,就不必使用out , ref等关键字了,直接定义一个Tuple类型,使用起来非常方便。

 1     //1 member
 2     Tuple<int> test = new Tuple<int>(1);
 3     //2 member ( 1< n <8)
 4     Tuple<int, int> test2 = Tuple.Create<int, int>(1, 2);
 5     //8 member, the last member must be tuple type.
 6     Tuple<int, int, int, int, int, int, int, Tuple<int>> test3
 7             = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));
 8 
 9     //output
10     Console.WriteLine(test.Item1);
11     Console.WriteLine(test2.Item1 + ", " + test2.Item2);
12     Console.WriteLine(test3.Item1 + ", " + test3.Item2 + ", " + test3.Item3 + ", " + test3.Item4
13             + ", " + test3.Item5 + ", " + test3.Item6 + ", " + test3.Item7 + ", " + test3.Rest.Item1);

更多嵌套定义的例子

 1     //2 member, the second member is the nest type tuple.
 2     Tuple<int, Tuple<int>> test4 = new Tuple<int, Tuple<int>>(1, new Tuple<int>(2));
 3     //10 member,the 8th member is the nest type tuple.
 4     Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>> test5
 5         = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7,
 6             new Tuple<int, int, int>(8, 9, 10));
 7 
 8     //output
 9     Console.WriteLine(test4.Item1 + ", " + test4.Item2.Item1);
10     Console.WriteLine(test5.Item1 + ", " + test5.Item2 + ", " + test5.Item3 + ", " + test5.Item4
11         + ", " + test5.Item5 + ", " + test5.Item6 + ", " + test5.Item7 + ", "
12         + test5.Rest.Item1 + ", " + test5.Rest.Item2 + ", " + test5.Rest.Item3);
posted @ 2015-03-26 15:27  天琊蓝  阅读(20643)  评论(0编辑  收藏  举报