这与我认为我对复制字典的理解背道而驰。说,我有以下代码:
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
我原以为更改复制的字典不会更改原始字典,但我的代码并非如此。
我究竟做错了什么?