官术网_书友最值得收藏!

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()}");
主站蜘蛛池模板: 满城县| 云和县| 扶沟县| 屏边| 青海省| 维西| 英德市| 福建省| 岫岩| 醴陵市| 余姚市| 连州市| 正镶白旗| 太保市| 莆田市| 麻栗坡县| 长乐市| 资源县| 印江| 分宜县| 桐梓县| 勃利县| 三亚市| 余庆县| 苍溪县| 堆龙德庆县| 四川省| 临洮县| 巨鹿县| 瑞昌市| 贵阳市| 大荔县| 青川县| 响水县| 遂昌县| 宁德市| 兰西县| 马公市| 三穗县| 汉源县| 宁强县|