Code Fix

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

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

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

 1  class Ticket {
 2      public readonly int EventId = 7;
 3      public int Seats = 0;
 4      public void Book() {
 5          _______ = 4;
               ^
 6      }
 7  }
 8  class Program {
 9      static void Main(string[] args) {
10          Ticket t = new Ticket();
11          t.Book();
12          System.Console.WriteLine(t.Seats);
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 の原因と直し方

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

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