共用方式為


編譯器錯誤 CS1656

更新:2007 年 11 月

錯誤訊息

無法指派給 'variable',因為它是 'read-only variable type'

在唯讀的情況下指派變數的值時就會發生這個錯誤。唯讀的情況包括 foreach 反覆運算變數、using 變數及 fixed 變數。若要解決這個錯誤,請避免在 using 區塊、foreach 陳述式及 fixed 陳述式中指派值給陳述式變數。

範例

下列範例會產生錯誤 CS1656,因為嘗試取代 foreach 迴圈內集合的完整項目。解決這個錯誤的一個方法是將 foreach 迴圈變更為 for 迴圈。另一個在此並未說明的方法為,修改現有項目的成員。對於 class 比較有可能這樣做,但對 struct 較困難。

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
        }
    }
}