Compiler Error CS0134
“variable”的类型为“type”。只能用 null 对引用类型(字符串除外)的常量字段进行初始化。
常量表达式是可在编译时可完全计算的表达式。由于应用 new 运算符是创建引用类型的非空值的唯一方法,并且常量表达式中不允许使用 new 运算符,因此除字符串外,引用类型常量的唯一可能值为 null。
如果尝试创建 const 字符串数组时遇到此错误,则解决方案是使该数组成为只读数组,并在构造函数中将其初始化。
下面的示例生成 CS0134。
// CS0134.cs
// compile with: /target:library
class MyTest {}
class MyClass
{
const MyTest test = new MyTest(); // CS0134
//OK
const MyTest test2 = null;
const System.String test3 = "test";
}