gpt4 book ai didi

C# 如何创建和初始化 ValueTuples 的静态数组?

转载 作者:行者123 更新时间:2023-12-02 03:20:38 24 4
gpt4 key购买 nike

我想初始化 ValueTuples 的静态只读数组,我想使用此 SO answer 中的方法:

var tupleList = new (int Index, string Name)[]
{
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};

但它不适用于静态成员,我必须声明 tupleList 的类型。我可以像这样将其作为元组来执行,但我不知道如何将其作为 ValueTuple 来执行:

static readonly Tuple<uint, string>[] tupleList= new Tuple<uint, string>[]
{
new Tuple<uint, string>(0x1, "string1"),
...
};

但如果我能找出正确的类型,我更愿意使用更清晰的格式,到目前为止我已经尝试了多种类型,但没有成功。

最佳答案

您不能使用“更干净的”var(隐式,但仍然强类型)类型,但您可以按照评论者的建议初始化元组。您可以摆脱的“最干净”的是这个,它在数组上使用类型推断:

(int Index, string Name)[] tupleList = {
(1, "cow"),
(5, "chickens"),
(1, "airplane")
};

这至少可以让您避免两次指定类型,这是人们使用 var 的原因之一。

该语言不支持在声明成员变量时使用var。对于静态字段和实例字段都是如此。

有一个historic reason为了这。这并不是说如果您提出更改并且经过社区审查就不能更改。

关于C# 如何创建和初始化 ValueTuples 的静态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com