Code Fix

上級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)

空欄を埋めてビルドを通す

広告
広告スロット(未設定)

A readonly field cannot be assigned to の原因と直し方

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)