上級 › A readonly field cannot be assigned to の原因と直し方 › パターン2
A readonly field cannot be assigned to の原因と直し方
readonly修飾子を付けたフィールドを、コンストラクタや初期化子以外の場所で書き換えようとすると出るコンパイルエラーです。
1 class Product { 2 public readonly string Id = "P-1"; 3 public int Stock = 0; 4 public void Restock() { 5 _____ = 20; ^ 6 } 7 } 8 class Program { 9 static void Main(string[] args) { 10 Product p = new Product(); 11 p.Restock(); 12 System.Console.WriteLine(p.Stock); 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)
空欄を埋めてビルドを通す
Idは商品を識別するための値なので変更させたくありません。readonlyにすることで代入をコンパイル時に防げます。
次の問題