上級 › A readonly field cannot be assigned to の原因と直し方 › パターン4
A readonly field cannot be assigned to の原因と直し方
readonly修飾子を付けたフィールドを、コンストラクタや初期化子以外の場所で書き換えようとすると出るコンパイルエラーです。
1 class Account { 2 public readonly string Owner = "Alice"; 3 public int Balance = 0; 4 public void Deposit() { 5 _______ = 100; ^ 6 } 7 } 8 class Program { 9 static void Main(string[] args) { 10 Account acc = new Account(); 11 acc.Deposit(); 12 System.Console.WriteLine(acc.Balance); 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)
空欄を埋めてビルドを通す
Ownerはreadonlyなので、コンストラクタの外にあるDepositメソッドから代入することはできません。
次の問題