编译器错误 CS0191
更新:2007 年 11 月
错误消息
无法对属性或索引器“name”赋值 -- 它是只读的
readonly 字段只能在构造函数或声明中获得赋值。有关更多信息,请参见构造函数(C# 编程指南)。
如果 readonly 字段为 static,但构造函数没有标记为 static,也会导致 CS0191。
示例
下面的示例生成 CS0191。
// CS0191.cs
class MyClass
{
public readonly int TestInt = 6; // OK to assign to readonly field in declaration
MyClass()
{
TestInt = 11; // OK to assign to readonly field in constructor
}
public void TestReadOnly()
{
TestInt = 19; // CS0191
}
public static void Main()
{
}
}