c#组元(Tuple)的使用

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

//1 member
    Tuple<int> test = new Tuple<int>(1);
    //2 member ( 1< n <8)
    Tuple<int, int> test2 = Tuple.Create<int, int>(1, 2);
    //8 member, the last member must be tuple type.
    Tuple<int, int, int, int, int, int, int, Tuple<int>> test3
            = new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));

    //output
    Console.WriteLine(test.Item1);
    Console.WriteLine(test2.Item1 + ", " + test2.Item2);
    Console.WriteLine(test3.Item1 + ", " + test3.Item2 + ", " + test3.Item3 + ", " + test3.Item4
            + ", " + test3.Item5 + ", " + test3.Item6 + ", " + test3.Item7 + ", " + test3.Rest.Item1);

更多嵌套定义的例子

//2 member, the second member is the nest type tuple.
    Tuple<int, Tuple<int>> test4 = new Tuple<int, Tuple<int>>(1, new Tuple<int>(2));
    //10 member,the 8th member is the nest type tuple.
    Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>> test5
        = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7,
            new Tuple<int, int, int>(8, 9, 10));

    //output
    Console.WriteLine(test4.Item1 + ", " + test4.Item2.Item1);
    Console.WriteLine(test5.Item1 + ", " + test5.Item2 + ", " + test5.Item3 + ", " + test5.Item4
        + ", " + test5.Item5 + ", " + test5.Item6 + ", " + test5.Item7 + ", "
        + test5.Rest.Item1 + ", " + test5.Rest.Item2 + ", " + test5.Rest.Item3);

 转自:https://www.cnblogs.com/makesense/p/4368899.html

posted @ 2019-03-23 18:33  黄树强  阅读(2976)  评论(0编辑  收藏  举报