是否可以在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