加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 混淆哈希表的浅层副本

发布时间:2020-12-15 17:27:41 所属栏目:百科 来源:网络整理
导读:关于浅层复制和哈希表的深层复制,我遇到了一些文章/解释,我读的越多,我就越困惑. 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 Has
关于浅层复制和哈希表的深层复制,我遇到了一些文章/解释,我读的越多,我就越困惑.

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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读