共用方式為


編譯器錯誤 CS0191

更新:2007 年 11 月

錯誤訊息

無法指定屬性或索引子 'name' -- 其為唯讀

readonly 欄位只會使用建構函式 (Constructor) 或宣告中的指派。如需詳細資訊,請參閱建構函式 (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()
    {
    }
}