编译器错误 CS0191

无法对属性或索引器“name”赋值 -- 它是只读的

readonly 字段只能采用构造函数或声明中的一个赋值。 有关详细信息,请参阅构造函数

如果 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()  
    {  
    }  
}