[C#7] 1.Tuples(元组)
1. 老版本代碼
?
class Program
{
? ? static void Main(string[] args)
? ? {
? ? ? ? var fullName = GetFullName();
? ? ? ? Console.WriteLine(fullName.Item1);// Item1,2,3不能忍,,,
? ? ? ? Console.WriteLine(fullName.Item2);
? ? ? ? Console.WriteLine(fullName.Item3);
? ? }
? ? static Tuple<string, string, string> GetFullName() => new Tuple<string, string, string>("first name", "blackheart", "last name");
}
在有些場景下,我們需要一個方法返回一個以上的返回值,微軟在.NET 4中引入了Tuple這個泛型類,可以允許我們返回多個參數(shù),每個參數(shù)按照順序被命名為?Item1;Item2,Item3 ,算是部分的解決了我們的問題,但是對于強迫癥程序員來說,Item1,2,3的命名簡直是不能忍的,,,so,在C#7中,引入了一個新的泛型類型ValueTuple<T>來解決這個問題,這個類型位于一個單獨的dll(System.ValueTuple)中,可以通過nuget來引入到你當前的項目中(https://www.nuget.org/packages/System.ValueTuple/)。
2. ValueTuple
不廢話,直接看代碼:
class Program
{
? ? static void Main(string[] args)
? ? {
? ? ? ? var fullName = GetFullName();
? ? ? ? Console.WriteLine(fullName.First); ?// 終于可以不是Item1,2,3了,,,
? ? ? ? Console.WriteLine(fullName.Middle);
? ? ? ? Console.WriteLine(fullName.Last);
? ? }
? ? static (string First, string Middle, string Last) GetFullName() => ("first name", "blackheart", "last name");
}
看出來差別了嗎?我們終于可以用更直觀的名字來替換掉該死的"Item1,2,3"了,看起來很棒吧。但是貌似我們并沒有用到上面我提到的System.ValueTuple,我們翻開編譯后的程序集看看:
internal class Program
{
? ? private static void Main(string[] args)
? ? {
? ? ? ? ValueTuple<string, string, string> fullName = Program.GetFullName();
? ? ? ? Console.WriteLine(fullName.Item1); // 原來你還是Item1,2,3,,,FUCK!!!
? ? ? ? Console.WriteLine(fullName.Item2);
? ? ? ? Console.WriteLine(fullName.Item3);
? ? }
? ? [TupleElementNames(new string[]
? ? {
? ? ? ? ? ? "First",
? ? ? ? ? ? "Middle",
? ? ? ? ? ? "Last"
? ? })]
? ? private static ValueTuple<string, string, string> GetFullName()
? ? {
? ? ? ? return new ValueTuple<string, string, string>("first name", "blackheart", "last name");
? ? }
}
不看不知道,一看嚇一跳,原來我們的 fullName.First; 編譯后居然還是 fullName.Item1 ,真是日了狗了。。。
不同之處在于GetFullName這個方法,編譯器把我們簡化的語法形式翻譯成了?ValueTuple<string, string, string> ,還給加了一個新的Attribute(TupleElementNamesAttribute),然后把我們自定義的非常直觀友好的“First”,"Middle","Last"當作元數(shù)據(jù)給存起來了。TupleElementNamesAttribute和ValueTuple一樣,位于System.ValueTuple的單獨dll中。
3. 總結(jié)
新的語法形式確實直觀友好了好多,but,本質(zhì)依然是借助泛型類型來實現(xiàn)的,同時也需要編譯器對新語法形式的支持。
了解了本質(zhì)是什么東西之后,以后在項目中環(huán)境允許的話,就放心大膽的使用吧(類型ValueTuple可以出現(xiàn)的地方,(first,last)這種新語法形式均可以)。
參考:https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
原文地址:http://www.cnblogs.com/linianhui/p/csharp7_tuple.html
.NET社區(qū)新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注
總結(jié)
以上是生活随笔為你收集整理的[C#7] 1.Tuples(元组)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Visual Studio 2017发布
- 下一篇: C#7.0之ref locals and