컴파일러 오류 CS1654

업데이트: 2007년 11월

오류 메시지

'read-only variable type'인 'variable'의 멤버는 수정할 수 없습니다.
Cannot modify members of 'variable' because it is a 'read-only variable type'

이 오류는 특수한 구문 내에 있어서 읽기 전용인 변수의 멤버를 수정하려고 할 때 발생합니다.

일반적으로 이 오류가 발생하는 영역 중 하나는 foreach 루프 내부입니다. 이 오류는 컬렉션 요소의 값을 수정하기 위한 컴파일 타임 오류입니다. 따라서 구조체를 비롯하여 값 형식인 요소는 수정할 수 없습니다. 요소가 참조 형식인 컬렉션에서는 각 요소의 액세스 가능한 멤버를 수정할 수 있지만 전체 요소를 추가, 제거 또는 대체하려고 하면 컴파일러 오류 CS1656이 발생합니다.

예제

다음 예제에서는 Book이 struct이기 때문에 CS1654 오류가 발생하는 경우를 보여 줍니다. 이 오류를 수정하려면 struct를 클래스로 변경합니다.

using System.Collections.Generic;
using System.Text;

namespace CS1654
{

    struct Book
    {
        public string Title;
        public string Author;
        public double Price;
        public Book(string t, string a, double p)
        {
            Title=t;
            Author=a;
            Price=p;

        }
    }

    class Program
    {
        List<Book> list;
        static void Main(string[] args)
        {
             //Use a collection initializer to initialize the list
            Program prog = new Program();
            prog.list = new List<Book>();
            prog.list.Add(new Book ("The C# Programming Language",
                                    "Hejlsberg, Wiltamuth, Golde",
                                     29.95));
            prog.list.Add(new Book ("The C++ Programming Language",
                                    "Stroustrup",
                                     29.95));
            prog.list.Add(new Book ("The C Programming Language",
                                    "Kernighan, Ritchie",
                                    29.95));
            foreach(Book b in prog.list)
            {
                //Compile error if Book is a struct
                //Make Book a class to modify its members
                b.Price +=9.95; // CS1654
            }

        }
    }
}