我在浅层复制和哈希表的深层复制方面遇到了一些文章/解释,我读的越多,我就越困惑。
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";
如果Case2和Case3是浅层复制,结果不应该与Case1相同吗?
这是否也发生在List,ArrayList等上?
答案 0 :(得分:2)
在案例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());