C#字典<>和可变密钥 [英] C# Dictionary<> and mutable keys

查看:178
本文介绍了C#字典<>和可变密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被告知,原因是多方面的字符串之一是不可变的C#规范是为了避免按键哈希表的问题,改变的时候提到了字符串键改变它们的内容。

I was told that one of the many reasons strings were made immutable in the C# spec was to avoid the issue of HashTables having keys changed when references to the string keys altered their content.

词典&所述;>类型允许引用类型被用作一个关键。如何字典避免导致错位的价值观改变的关键问题?有制成的物体的成员逐一克隆作为密钥使用时

The Dictionary<> type allows reference types to be used as a key. How does the dictionary avoid the issue of altered keys that lead to "misplaced" values? Is there a memberwise clone made of an object when used as a key?

推荐答案

词典&LT; TKEY的,TValue&GT; 类型没有尝试,以防止修改键使用的用户。这纯粹是留给开发人员负责在未变异的关键。

The Dictionary<TKey,TValue> type makes no attempt to protect against the user modifying the key used. It is purely left up to the developer to be responsible in not mutating the key.

如果你觉得这个有点真的是唯一明智路线 词典&LT; TKEY的,TValue&GT; 可以采取。考虑做一个操作,如对象的成员逐一克隆的含义。为了彻底你需要做一个深克隆,因为这将有可能在关键引用的对象也发生突变,从而影响散列code。所以,现在的表使用的每个按键都有它的克隆,以防止突变完整的对象图。这将是这两个车和有可能非常昂贵的操作。

If you think about this a bit this is really the only sane route that Dictionary<TKey,TValue> can take. Consider the implication of doing an operation like a memberwise clone on the object. In order to be thorough you'd need to do a deep clone because it will be possible for an object referenced in the key to also be mutated and hence affect the hash code. So now every key used in the table has it's full object graph cloned in order to protect against mutation. This would be both buggy and possibly a very expensive operation.

这篇关于C#字典&LT;&GT;和可变密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆