首页 > 技术文章 > [C#7] 1.Tuples(元组)

webenh 原文

1. 老版本代码

复制代码
 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var fullName = GetFullName();
 6 
 7         Console.WriteLine(fullName.Item1);// Item1,2,3不能忍,,,
 8         Console.WriteLine(fullName.Item2);
 9         Console.WriteLine(fullName.Item3);
10     }
11     static Tuple<string, string, string> GetFullName() => new Tuple<string, string, string>("first name", "blackheart", "last name");
12 }
复制代码

在有些场景下,我们需要一个方法返回一个以上的返回值,微软在.NET 4中引入了Tuple这个泛型类,可以允许我们返回多个参数,每个参数按照顺序被命名为 Item1;Item2,Item3 ,算是部分的解决了我们的问题,但是对于强迫症程序员来说,Item1,2,3的命名简直是不能忍的,,,so,在C#7中,引入了一个新的泛型类型ValueTuple<T>来解决这个问题,这个类型位于一个单独的dll(System.ValueTuple)中,可以通过nuget来引入到你当前的项目中(https://www.nuget.org/packages/System.ValueTuple/)。

2. ValueTuple

不废话,直接看代码:

复制代码
 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var fullName = GetFullName();
 6 
 7         Console.WriteLine(fullName.First);  // 终于可以不是Item1,2,3了,,,
 8         Console.WriteLine(fullName.Middle);
 9         Console.WriteLine(fullName.Last);
10     }
11 
12     static (string First, string Middle, string Last) GetFullName() => ("first name", "blackheart", "last name");
13 }
复制代码

看出来差别了吗?我们终于可以用更直观的名字来替换掉该死的"Item1,2,3"了,看起来很棒吧。但是貌似我们并没有用到上面我提到的System.ValueTuple,我们翻开编译后的程序集看看:

复制代码
 1 internal class Program
 2 {
 3     private static void Main(string[] args)
 4     {
 5         ValueTuple<string, string, string> fullName = Program.GetFullName();
 6         Console.WriteLine(fullName.Item1); // 原来你还是Item1,2,3,,,FUCK!!!
 7         Console.WriteLine(fullName.Item2);
 8         Console.WriteLine(fullName.Item3);
 9     }
10 
11     [TupleElementNames(new string[]
12     {
13             "First",
14             "Middle",
15             "Last"
16     })]
17     private static ValueTuple<string, string, string> GetFullName()
18     {
19         return new ValueTuple<string, string, string>("first name", "blackheart", "last name");
20     }
21 }
复制代码

不看不知道,一看吓一跳,原来我们的 fullName.First; 编译后居然还是 fullName.Item1 ,真是日了狗了。。。

不同之处在于GetFullName这个方法,编译器把我们简化的语法形式翻译成了 ValueTuple<string, string, string> ,还给加了一个新的Attribute(TupleElementNamesAttribute),然后把我们自定义的非常直观友好的“First”,"Middle","Last"当作元数据给存起来了。TupleElementNamesAttribute和ValueTuple一样,位于System.ValueTuple的单独dll中。

3. 总结

新的语法形式确实直观友好了好多,but,本质依然是借助泛型类型来实现的,同时也需要编译器对新语法形式的支持。

了解了本质是什么东西之后,以后在项目中环境允许的话,就放心大胆的使用吧(类型ValueTuple可以出现的地方,(first,last)这种新语法形式均可以)。

参考:https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

作者:Blackheart

推荐阅读