更新:2007 年 11 月

错误消息

无法给“variable”赋值,因为它是“read-only variable type”

当变量赋值发生在只读上下文中时,将出现此错误。只读上下文包括 foreach 迭代变量、using 变量和 fixed 变量。若要解决此错误,请避免在 using 块、foreach 语句和 fixed 语句中给变量赋值。

示例

以下示例生成错误 CS1656,因为它试图替换 foreach 循环内的集合中的所有元素。解决此错误的一种方法是将 foreach 循环更改为 for 循环。另一种方法(此处未显示)是修改现有元素的成员;这可能对类起作用,但对结构不起作用。

 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CS1654_2
{

    class 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
    {
        private List<Book> list;
        static void Main(string[] args)
        {
            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)
            {
                // Cannot modify an entire element in a foreach loop 
                // even with reference types.
                // Use a for or while loop instead
                if(b.Title == "The C Programming Language")
                    b = new Book("Programming Windows, 5th Ed.", "Petzold", 29.95); //CS1654
            }

            //With a for loop you can modify elements
            //for(int x = 0; x < prog.list.Count; x++)
            //{
            //    if(prog.list[x].Title== "The C Programming Language")
            //        prog.list[x] = new Book("Programming Windows, 5th Ed.", "Petzold", 29.95);
            //}
            //foreach(Book b in prog.list)
            //    Console.WriteLine(b.Title);

        }
    }
}

下面的示例演示如何在除 foreach 循环之外的其他上下文中生成 CS1656:

 复制代码
// CS1656.cs
// compile with: /unsafe
using System;

class C : IDisposable
{
    public void Dispose() { }
}

class CMain
{
    unsafe public static void Main()
    {
        using (C c = new C())
        {
            c = new C(); // CS1656
        }

        int[] ary = new int[] { 1, 2, 3, 4 };
        fixed (int* p = ary)
        {
            p = null; // CS1656
        }
    }
}