C# 混淆哈希表的浅拷贝
我遇到了一些关于哈希表浅拷贝和深拷贝的文章/解释,读得越多,我就越困惑C# 混淆哈希表的浅拷贝,c#,asp.net,hashtable,C#,Asp.net,Hashtable,我遇到了一些关于哈希表浅拷贝和深拷贝的文章/解释,读得越多,我就越困惑 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); // cas
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不同
List、ArrayList等也会发生这种情况吗?在案例1中,
ht2
和ht
都引用了哈希表的相同实例
在案例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());
var original=newdictionary();
原始[10]=新的StringBuilder();
var副本=新的口述(原件);
复制[20]=新建StringBuilder();
//我们有两张不同的地图。。。
Assert.IsFalse(原件.ContainsKey(20));
//但他们都提到了一个单一的StringBuilder在条目中为10。。。
副本[10]。追加(“Foo”);
Assert.AreEqual(“Foo”,原文[10].ToString());
作为旁白-如果您使用的是.NET 3.5,为什么还要使用ArrayList
和Hashtable
?非常喜欢泛型类型。hi@JonSkeet,thx用于指出泛型类型。我已经转到泛型类型了。直到你在这里指出它(用一个很好的例子),我才意识到这种行为。谢谢。