字符串以外的引用类型的常量字段只能用null错误进行初始化常量、字段、初始化、只能用

2023-09-03 12:02:57 作者:牛逼轰轰炸满天

我想创建一个二维数组存储一些值不改变这样的。

I'm trying to create a 2D array to store some values that don't change like this.

const int[,] hiveIndices = new int[,] {
{200,362},{250,370},{213,410} , 
{400,330} , {380,282} , {437, 295} ,
{325, 405} , {379,413} ,{343,453} , 
{450,382},{510,395},{468,430} ,
{585,330} , {645,340} , {603,375}
};

不过,在编译时我收到此错误

But while compiling I get this error

hiveIndices is of type 'int[*,*]'. 
A const field of a reference type other than string can only be initialized with null.

如果我修改常量为静态,它编译。我不知道如何添加const的量词应该引起这种行为。

If I change const to static, it compiles. I don't understand how adding the const quantifier should induce this behavior.

推荐答案

其实你正试图使的阵列的 - 这是引用类型 - 常量 - 这不会影响其价值的可变性所有(你仍然可以发生变异数组内的任何值) - 使阵列只读将使编译,但没有收到预期的效果无论是。恒EX pressions已经被完全在编译时进行评估,因此,新的运营商是不允许的。

Actually you are trying to make the array - which is a reference type - const - this would not affect mutability of its values at all (you still can mutate any value within the array) - making the array readonly would make it compile, but not have the desired effect either. Constant expressions have to be fully evaluated at compile time, hence the new operator is not allowed.

您可能会寻找ReadOnlyCollection<T>

有关更多看到相应的编译器错误CS0134 :

一个恒定的-EX pression是一个前pression,可以在充分评估   编译时。因为只有这样,才能建立一个非空值   引用类型是应用新的操作者,而且由于新   操作者未在一个恒定的前pression允许的,唯一可能的   值的引用类型不是字符串其他常量为空。

A constant-expression is an expression that can be fully evaluated at compile-time. Because the only way to create a non-null value of a reference-type is to apply the new operator, and because the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.