0
class Numbers
{
    List<int> num;
    public Numbers()
    {
        num = new List<int> { 1, 2, 3, 4 };
    }
    public List<int> GetNumbers
    {
        get
        {
            return num;
        }

    }
}
class Program
{
    static void Main(string[] args)
    {
        Numbers n = new Numbers();
        List<int> l = n.GetNumbers;
        n.GetNumbers[0] = 10; //Modification done in the original set.
        foreach (int x in l)
        {
            Console.WriteLine(x);
        }
        Console.ReadLine();
    }

}

为什么即使 GetNumbers 属性是只读的,原始数字列表 {1,2,3,4) 的值也会通过 GetNumbers 属性进行修改。

4

1 回答 1

4

readonly关键字意味着变量是只读的——但它不保证对象本身是不可变的。举例说明:

class Numbers
{
    readonly List<int> num;
    public Numbers()
    {
        // ok - can write to read-only variables in the owner's constructor
        num = new List<int> { 1, 2, 3, 4 };
    }

    void Test()
    {
        // this is fine -- I'm not writing to "num", just changing its state
        num.Clear();

        // compiler error: "a readonly field cannot be assigned to"
        num = new List<int>();
    }
}

如果你想要一个只读集合,有 .Net 类型可以达到这个目的;例如见ReadOnlyCollection<T>


相关:Eric Lippert 关于不同类型不变性的著名文章

于 2013-07-22T22:36:04.780 回答