編譯器錯誤 CS1654
更新:2007 年 11 月
錯誤訊息
無法修改 'variable' 的成員,因為它是 'read-only variable type'
當您嘗試修改唯讀變數的成員時,由於它是位於特殊建構中,因此會發生這個錯誤。
一般會發生此錯誤的區域是在 foreach 迴圈中。這是編譯時期錯誤,用以修改集合項目的值。因此,您無法對實值型別的項目進行修改,包括結構。在項目為參考型別的集合中,您可以修改每個項目的可存取成員,但嘗試加入、移除或取代完整項目將會產生編譯器錯誤 CS1656。
範例
下列範例會產生錯誤 CS1654,因為 Book 為 struct。若要修正錯誤,請將 struct 變更為 class。
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
}
}
}
}