从this 帖子中复制我的答案,因为现在可以为元组中的属性命名。
从 C# v7.0 开始,现在可以命名元组属性,以前默认为 Item1、Item2 等名称。
命名元组文字的属性:
var myDetails = (MyName: "RBT_Yoga", MyAge: 22, MyFavoriteFood: "Dosa");
Console.WriteLine($"Name - {myDetails.MyName}, Age - {myDetails.MyAge}, Passion - {myDetails.MyFavoriteFood}");
控制台输出:
姓名 - RBT_Yoga,年龄 - 22,激情 - Dosa
从方法返回元组(具有命名属性):
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 ("Rasik", "Bihari", "Rasik-PC", 1000);
}
控制台输出:
员工详细信息:Rasik,Bihari,Rasik-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 - 牛
5 - 鸡
1 - 飞机
我希望我已经涵盖了所有内容。如果有什么我遗漏的,请在 cmets 中给我反馈。
注意:我的代码 sn-ps 正在使用 C# v7 的字符串插值功能,详细说明 here。