[英]IDictionary<TKey, TValue> implementation and contract for replacing values
Is there a "contract" for the interface IDictionary<TKey, TValue>
I should follow when implementing value replacement with this[key] = newValue
? 接口IDictionary<TKey, TValue>
是否有“契约”,我应该在使用this[key] = newValue
实现值替换时遵循? An example: 一个例子:
IDictionary<MyKey, string> dict = CreateEmptyDict();
var k1 = new MyKey(123);
var k2 = new MyKey(123);
dict.Add(k1, "foo");
dict[k2] = "bar";
k1 and k2 are such that k1.Equals(k2)
and they have the same hash code, but they are reference types so ReferenceEquals(k1, k2) == false
. k1和k2是k1.Equals(k2)
并且它们具有相同的哈希码,但它们是引用类型,因此ReferenceEquals(k1, k2) == false
。
The BCL Dictionary<TKey, TValue>
will contain (k1, "bar")
. BCL Dictionary<TKey, TValue>
将包含(k1, "bar")
。 My question is: is this a "contract" I really should follow for any implementation of IDictionary<TKey, TValue>
or can I let my implementation contain (k2, "bar")
if it is easier to do so in the underlying data structure? 我的问题是:这是一个“合同”我真的应该遵循IDictionary<TKey, TValue>
任何实现,或者如果在底层数据结构中更容易这样做(k2, "bar")
我可以让我的实现包含(k2, "bar")
?
It's implementation-specific at least to some extent. 这是实现特定的,至少在一定程度上。 For example, Dictionary<,>
allows you to specify an IEqualityComparer<T>
to use to check keys for equality, and SortedDictionary<,>
doesn't use Equals
and GetHashCode
at all - instead, it uses IComparer<T>
to check for key ordering . 例如, Dictionary<,>
允许您指定用于检查键是否相等的IEqualityComparer<T>
,而SortedDictionary<,>
根本不使用Equals
和GetHashCode
- 而是使用IComparer<T>
来检查密钥订购 。
It would be entirely reasonable to create a dictionary which relied on solely reference equality - but make sure you document that very carefully. 创建一个仅依赖于引用相等的字典是完全合理的 - 但请确保您非常仔细地记录。 I would note that you don't really need to implement IDictionary<,>
yourself to do that... you just need to use Dictionary<,>
and custom equality comparer which uses reference equality and RuntimeHelpers.GetHashCode()
to fetch the hash code that Object.GetHashCode()
would use if it weren't overridden. 我会注意到你并不需要自己实现IDictionary<,>
这样做...你只需要使用Dictionary<,>
和使用引用相等的自定义相等比较器和RuntimeHelpers.GetHashCode()
来获取哈希Object.GetHashCode()
在未被覆盖的情况下将使用的代码。
It would be very, very weird for a dictionary to be implemented so that you could add the exact same value as a key multiple times - but how you judge whether keys are actually equal is a different matter, IMO. 对于要实现的字典来说非常非常奇怪,以便您可以多次添加与键完全相同的值 - 但是如何判断键实际上是否相等则是另一回事,IMO。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.