从这篇文章中复制我的答案,因为它更适合这里。
从c# v7.0开始,现在可以将元组属性命名为Item1、Item2等早先默认的名称。
命名元组字面量的属性:
var myDetails = (MyName: "Foo", MyAge: 22, MyFavoriteFood: "Bar");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");
控制台的输出:
Name - Foo, Age - 22, Passion - Bar
从一个方法返回元组(有命名属性):
static void Main(string[] args)
{
var empInfo = GetEmpInfo();
Console.WriteLine($"Employee Details: {empInfo.firstName}, {empInfo.lastName}, {empInfo.computerName}, {empInfo.Salary}");
}
static (string firstName, string lastName, string computerName, int Salary) GetEmpInfo()
{
//This is hardcoded just for the demonstration. Ideally this data might be coming from some DB or web service call
return ("Foo", "Bar", "Foo-PC", 1000);
}
控制台的输出:
Employee Details: Foo, Bar, Foo-PC, 1000
创建具有命名属性的元组列表
var tupleList = new List<(int Index, string Name)>
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};
foreach (var tuple in tupleList)
Console.WriteLine($"{tuple.Index} - {tuple.Name}");
控制台输出:
1 - cow
5 - chickens
1 - airplane
注意:本文中的代码片段使用了c# v6的字符串插值特性。