关于浅层复制和哈希表的深层复制,我遇到了一些文章/解释,我读的越多,我就越困惑.
Hashtable ht = new Hashtable();
ht.Add("1", "hello");
Hashtable ht2 = new Hashtable();
ht2 = ht; // case1: is this shallow copy?
ht2["1"] = "H2";
Hashtable ht3 = new Hashtable(ht); // case2: is this shallow copy?
ht3["1"] = "H3";
Hashtable ht4 = new Hashtable();
ht4 = (Hashtable)ht.Clone(); // case3: is this shallow copy?
ht4["1"] = "H4";
>案例1:结果,ht内容变化与ht2相同.
>案例2:结果,ht内容与ht3不同.
>案例3:结果,ht内容与ht4不同.
如果Case2和Case3是浅层复制,结果不应该与Case1相同吗?
这是否也发生在List,ArrayList等?
最佳答案 在案例1中,ht2和ht都引用了Hashtable的相同实例.
在情况2和3中,ht3和ht4指的是通过复制原始Hashtable条目而创建的不同对象.
请注意,即使采用“深度”副本(创建新映射),您仍然会复制引用.例如:
var original = new Dictionary<int, StringBuilder>();
original[10] = new StringBuilder();
var copy = new Dictoinary<int, StringBuilder>(original);
copy[20] = new StringBuilder();
// We have two different maps...
Assert.IsFalse(original.ContainsKey(20));
// But they both refer to a single StringBuilder in the entry for 10...
copy[10].Append("Foo");
Assert.AreEqual("Foo", original[10].ToString());