复制字典的意外结果

时间:2013-04-11 10:14:49

标签: c# .net dictionary

这违背了我对复制字典的理解。说,我有以下代码:

public class MyClass
{
    public string str1;

    public MyClass(string s)
    {
        str1 = s;
    }
}

Dictionary<string, MyClass> dic1 = new Dictionary<string, MyClass>();
dic1.Add("0", new MyClass("hello"));

//Make 'dic2' as a copy of 'dic1'
Dictionary<string, MyClass> dic2 = new Dictionary<string, MyClass>(dic1);

//Alter 'dic1'
dic1.ElementAt(0).Value.str1 += "!!!";

//I was expecting dic2 not to be altered, but IT IS!
Debug.Assert(dic2["0"].str1.Equals(dic1["0"].str1, StringComparison.Ordinal) == false);     //Result is true for equality

我原本期望更改复制的字典我不会更改原始字典,但我的代码不是这样。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

正如科拉克所说,你做了一个浅薄的副本。您正在复制对内存中对象的引用,而不是对象本身。现在,对于每个键,您有两个对象的引用。

您想要的是深层副本,请参阅此处:What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?