是否可以在C#7中创建ValueTuple列表?如何创建ValueTuple列表?
这样的:
List<(int example, string descrpt)> Method()
{
return Something;
}
是否可以在C#7中创建ValueTuple列表?如何创建ValueTuple列表?
这样的:
List<(int example, string descrpt)> Method()
{
return Something;
}
您正在寻找这样的语法:
List<(int, string)> list = new List<(int, string)>();
list.Add((3, "test"));
list.Add((6, "second"));
您可以使用这样的在你的情况下:
List<(int, string)> Method() =>
new List<(int, string)>
{
(3, "test"),
(6, "second")
};
您还可以返回之前命名值:
List<(int Foo, string Bar)> Method() =>
...
而且你可以接收值,而(重新)命名它们:
List<(int MyInteger, string MyString)> result = Method();
var firstTuple = result.First();
int i = firstTuple.MyInteger;
string s = firstTuple.MyString;
thx Guilherme,回答我的问题 – ArthNRick
它更好命名方法定义中的字段。 –
此语法最好应用于c# 6
,但可以在c# 7
被使用。其他答案更加正确,因为趋向于使用ValueTuple
而不是此处使用的Tuple
。你可以看到不同here为ValueTuple
List<Tuple<int, string>> Method()
{
return new List<Tuple<int, string>>
{
new Tuple<int, string>(2, "abc"),
new Tuple<int, string>(2, "abce"),
new Tuple<int, string>(2, "abcd"),
};
}
当然,你可以这样做:
List<(int example, string descrpt)> Method() => new List<int, string> { (2, "x") };
var data = Method();
Console.WriteLine(data.First().example);
Console.WriteLine(data.First().descrpt);
你为什么不尝试一下呢? –
因为这是*返回指定元组列表所需的语法,所以我几乎不愿意downvote。为什么这样问? –
我想这个问题是关于不是Method的返回类型,而是关于丢失的** Something **。 – quetzalcoatl