C# 字符串以外的引用类型的 const 字段只能初始化为 null 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9952990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A const field of a reference type other than string can only be initialized with null Error
提问by nikhil
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.
If I change const to static, it compiles. I don't understand how adding the const quantifier should induce this behavior.
如果我更改const to static,它会编译。我不明白添加 const 量词应该如何引起这种行为。
采纳答案by BrokenGlass
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 readonlywould 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.
实际上,您正在尝试制作数组- 这是一种引用类型 -const这根本不会影响其值的可变性(您仍然可以改变数组中的任何值) - 制作数组readonly会使它编译,但没有想要的效果。常量表达式必须在编译时完全计算,因此不允许使用 new 运算符。
You might be looking for ReadOnlyCollection<T>
您可能正在寻找 ReadOnlyCollection<T>
For more see the corresponding Compiler Error CS0134:
有关更多信息,请参阅相应的编译器错误 CS0134:
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.
常量表达式是可以在编译时完全计算的表达式。因为创建引用类型的非空值的唯一方法是应用 new 运算符,并且因为常量表达式中不允许使用 new 运算符,所以除了字符串之外的引用类型的常量的唯一可能值一片空白。

