0
点赞
收藏
分享

微信扫一扫

C# 组元Tuple


组元是C# 4.0引入的一个新特性.需要基于.NET Framework 4.0或者更高版本。组元使用泛型来简化一个类的定义。组元多用于方法的返回值,如果一个函数返回多个类型,这样就不在用 out\ref 等输出参数了,可以直接定义一个 Tuple 类型就可以了。

1.0 简单使用

//一个成员
Tuple<int> test = new Tuple<int>(1);
Console.WriteLine(test.Item1);

//两个成员
Tuple<int, double> test1 = new Tuple<int, double>(2, 2.3);
Console.WriteLine(test1.Item1 + test1.Item2);

2.0 嵌套使用

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

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

//非8个元素
Tuple<int, Tuple<string>> test2 = new Tuple<int, Tuple<string>>(3, new Tuple<string>("Nesting"));
Console.WriteLine(test2.Item1);
Console.WriteLine(test2.Item2);
//8个元素
Tuple<int, long, float, double, short, byte, char, Tuple<int>> test3 =
new Tuple<int, long, float, double, short, byte, char, Tuple<int>>(1,
2, 3.0f, 4, 5, 6, 'h', new Tuple<int>(8));
Console.WriteLine(test3.Item1 + test3.Rest.Item1);

举报

相关推荐

0 条评论