上級 › A readonly field cannot be assigned to の原因と直し方 › パターン1
A readonly field cannot be assigned to の原因と直し方
readonly修飾子を付けたフィールドを、コンストラクタや初期化子以外の場所で書き換えようとすると出るコンパイルエラーです。
1 class Config { 2 public readonly int MaxUsers = 100; 3 public int CurrentUsers = 0; 4 public void Reset() { 5 ____________ = 50; ^ 6 } 7 } 8 class Program { 9 static void Main(string[] args) { 10 Config c = new Config(); 11 c.Reset(); 12 System.Console.WriteLine(c.CurrentUsers); 13 } 14 }
Program.cs(5,9): error CS0191: A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer)
空欄を埋めてビルドを通す
readonlyなフィールドはコンストラクタ以外から代入できません。書き換えたい値は普通のフィールドにする必要があります。
次の問題