Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 引用类型而非字符串的常量字段只能用null错误初始化_C#_.net - Fatal编程技术网

C# 引用类型而非字符串的常量字段只能用null错误初始化

C# 引用类型而非字符串的常量字段只能用null错误初始化,c#,.net,C#,.net,我试图创建一个2D数组来存储一些不会像这样改变的值 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} }; 但是在编译时,

我试图创建一个2D数组来存储一些不会像这样改变的值

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}
};
但是在编译时,我得到了这个错误

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

如果我将
常量更改为static
,它将编译。我不明白如何添加常量量词会导致这种行为。

实际上,您正在尝试创建数组-这是一种引用类型-
常量-这根本不会影响其值的可变性。(您仍然可以变异数组中的任何值)-使数组
只读将使其可编译,但也不会达到预期效果。常量表达式必须在编译时完全求值,因此不允许使用新运算符

你可能在找

有关更多信息,请参见相应的:

常量表达式是一个可以在 编译时。因为创建 引用类型是应用新运算符,因为 常量表达式中不允许使用运算符,这是唯一可能的 除字符串以外的引用类型的常量的值为null


实际上,创建一个只读2d数组需要为它编写一个包装,因为
AsReadOnly
只支持一维零基数组:更多阅读,请看你的意思是我投了反对票,因为我的答案不是最好的?我没有投你的反对票,但可能是的-您的答案将使代码编译,但您仍然可以变异数组中的元素,这是OP想要防范的,谢谢。这可能太健谈了,但我是作为一个新用户问的。我应该删除我的答案还是更新它?最好的做法是什么?在这一点上,如果你没有更好的答案,你可以删除它,你会得到负面的声誉