在C# 7中创建一个System.ValueTuple数组

13

我的代码中有:

private static readonly ValueTuple<string, string>[] test = {("foo", "bar"), ("baz", "foz")};

但是当我编译我的代码时,我会得到:

TypoGenerator.cs(52,76):  error CS1026: Unexpected symbol `,', expecting `)'
TypoGenerator.cs(52,84):  error CS1026: Unexpected symbol `)', expecting `)'
TypoGenerator.cs(52,94):  error CS1026: Unexpected symbol `,', expecting `)'
TypoGenerator.cs(52,103):  error CS1026: Unexpected symbol `)', expecting `)'
TypoGenerator.cs(117,42):  error CS1525: Unexpected symbol `('
TypoGenerator.cs(117,58):  error CS1525: Unexpected symbol `['

如何正确创建和初始化ValueTuples的数组?

3个回答

14
尝试使用new创建数组实例,使用new关键字创建元组实例。
private static readonly ValueTuple<string, string>[] test = new ValueTuple<string, string>[]{
        new ValueTuple<string, string>("foo", "bar"), 
        new ValueTuple<string, string>("baz", "foz")
};

或使用C#7元组语法

private static readonly ValueTuple<string, string>[] test = new ValueTuple<string, string>[]{
        ("foo", "bar"), 
        ("baz", "foz")
};

更新:

目前,该问题和本答案中的所有声明都可以与Rider 2017.1 build #RD-171.4456.1432和.NET Core 1.0.4正常工作。其中最简单的一个是@ZevSpitz在评论中提到的,代码如下:

private static readonly (string, string)[] test = {("foo", "bar"), ("baz", "foz")};

不需要为ValueTuple添加特定类型。请注意,在.NET Core中,必须安装NuGet包System.ValueTuple


这个失败了:TypoGenerator.cs(53,18): error CS1026: Unexpected symbol ,', expecting )' TypoGenerator.cs(53,25): error CS1026: Unexpected symbol )', expecting )'``` TypoGenerator.cs(54,18): error CS1026: Unexpected symbol ,', expecting )' TypoGenerator.cs(54,25): error CS1026: Unexpected symbol )', expecting ) - Lett1
@Lett1 两个示例在 .NET Fiddle 上都可以运行。你尝试过使用 new 来创建数组元素的示例吗? - Nikolay K
结果发现,C#7元组语法在OSX上与Rider不兼容,但第一个解决方案可以正常工作。 - Lett1
1
在C# 7中,我认为您不需要在字段定义或新的数组表达式中使用ValueTuple名称-- private static readonly (string, string)[] test = new [] { ("foo","bar"), ("baz", "foz")}; - Zev Spitz
谢谢@ZevSpitz,几个月前这个语法有一些问题,正如OP所提到的。现在它已经可以正常工作了,所以我已经更新了我的答案。 - Nikolay K

11

使用 C# 7 语法声明和初始化数组 ValueTuple 的三个简短示例:

(int Alpha, string Beta)[] array1 = { (Alpha: 43, Beta: "world"), (99, "foo") };
(int Alpha, string Beta)[] array2 = { (43, "world"), (99, "foo") };
(int, string)[] array3 = { (43, "world"), (99, "foo") };   // Item1, Item2, ...

这些在VS2017中都可以正常编译。

Linq也可以是创建ValueTuple数组的好方法:

var foo = Enumerable.Range(1,10).Select(z=> (Alpha: 43, Beta: "world")).ToArray();

3
你可以这样创建一个新的元组:
var logos = new (string Name, string Uri)[]
{
    ("White", "white.jpg"),
    ("Black", "black.jpg"),
};

你能稍微解释一下你在这里做什么吗? - Johnny Rockex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接