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

C# How to create and initialize a static array of ValueTuples?

我想初始化一个 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"),
    ...
};

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

您不能使用 "cleaner" var(隐式,但仍然是强类型)类型,但您可以按照评论者的建议初始化元组。 "cleanest" 你可以逃脱的是这个,它在数组上使用类型推断:

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

这至少可以让您避免指定类型两次,这是人们使用 var.

的原因之一

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

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