- ASP.NET Core 2 High Performance(Second Edition)
- James Singleton
- 255字
- 2021-07-08 09:38:59
Tuples
One of the big new features in C# 7 is support for tuples. Tuples are groups of values, and you can now return them directly from method calls. You are no longer restricted to returning a single value. Previously, you could work around this limitation in a few suboptimal ways, including creating a custom complex object to return, perhaps with a Plain Old C# Object (POCO) or Data Transfer Object (DTO), which are the same thing. You could have also passed in a reference using the ref or out keyword, which are still not great although there are improvements to the syntax.
There was System.Tuple in C# 6, but it wasn't ideal. It was a framework feature, rather than a language feature, and the items were only numbered and not named. With C# 7 tuples, you can name the objects and they make a great alternative to anonymous types, particularly in LINQ query expression lambda functions. As an example, if you only want to work on a subset of the data available, perhaps when filtering a database table with an O/RM, such as Entity Framework, then you could use a tuple for this.
The following example returns a tuple from a method. You may need to add the System.ValueTuple NuGet package for this to work:
private static (int one, string two, DateTime three) GetTuple()
{
return (one: 1, two: "too", three: DateTime.UtcNow);
}
You can also use tuples in string interpolation and all the values will be rendered, as shown here:
Console.WriteLine($"Tuple = {GetTuple()}");
- Learning LibGDX Game Development(Second Edition)
- 騰訊iOS測試實踐
- Java Web基礎與實例教程(第2版·微課版)
- 人人都是網站分析師:從分析師的視角理解網站和解讀數據
- Learning Hunk
- 青少年信息學競賽
- Windows Phone 7.5:Building Location-aware Applications
- Python機器學習算法: 原理、實現與案例
- JavaScript應用開發實踐指南
- C語言程序設計簡明教程:Qt實戰
- PowerDesigner 16 從入門到精通
- Python預測分析實戰
- 高質量程序設計指南:C++/C語言
- C#網絡編程高級篇之網頁游戲輔助程序設計
- AI輔助編程Python實戰:基于GitHub Copilot和ChatGPT