我正在尝试创建一个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}
};
Run Code Online (Sandbox Code Playgroud)
但是在编译时我得到了这个错误
hiveIndices is of type 'int[*,*]'.
A const field of a reference type other than string can only be initialized with null.
Run Code Online (Sandbox Code Playgroud)
如果我改变const to static,它会编译.我不明白添加const量词应该如何引发这种行为.
Bro*_*ass 43
实际上你正在尝试创建数组 - 这是一个引用类型 - const这根本不会影响它的值的可变性(你仍然可以改变数组中的任何值) - 使数组readonly会使它编译,但没有期望的效果.必须在编译时对常量表达式进行全面计算,因此不允许使用new运算符.
你可能正在寻找 ReadOnlyCollection<T>
有关更多信息,请参阅相应的编译器错误CS0134:
constant-expression是一个可以在编译时完全评估的表达式.因为创建引用类型的非空值的唯一方法是应用new运算符,并且因为常量表达式中不允许使用new运算符,所以除了string之外的引用类型的常量的唯一可能值一片空白.
| 归档时间: |
|
| 查看次数: |
20329 次 |
| 最近记录: |