Code Fix

上級A readonly field cannot be assigned to の原因と直し方 › パターン3

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

readonly修飾子を付けたフィールドを、コンストラクタや初期化子以外の場所で書き換えようとすると出るコンパイルエラーです。

 1  class GameConfig {
 2      public readonly int MaxLevel = 99;
 3      public int CurrentLevel = 1;
 4      public void LevelUp() {
 5          ____________ = CurrentLevel + 1;
                  ^
 6      }
 7  }
 8  class Program {
 9      static void Main(string[] args) {
10          GameConfig g = new GameConfig();
11          g.LevelUp();
12          System.Console.WriteLine(g.CurrentLevel);
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 の原因と直し方

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

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