[英]My IEquatable is still using Object.GetHashcode for Dictionary<T>[]
I have something like the following to be a key for a generic dictionary. 我有类似下面的东西作为通用字典的关键。
class IMyClass<T> : IEquatable<IMyClass> where T : struct
{
//etc
}
class MyClass<T> : IMyClass<T> where T : struct
{
public bool Equals(IRatingKey<T> other)
{
//etc
}
}
From what I understand of EqualityComparer<T>.Default
, it should see that I have implemented IEquatable<T>
and therefore create an EqualityComparer on the fly. 根据我对
EqualityComparer<T>.Default
理解,它应该看到我已经实现了IEquatable<T>
,因此可以动态创建EqualityComparer。
Dictionary<TKey, TValue>
requires an equality implementation to determine whether keys are equal.Dictionary<TKey, TValue>
需要一个相等的实现来确定键是否相等。 If comparer is null, this constructor uses the default generic equality comparer,EqualityComparer<T>.Default
.如果comparer为null,则此构造函数使用默认的通用相等比较器
EqualityComparer<T>.Default
。 If typeTKey
implements theSystem.IEquatable<T>
generic interface, the default equality comparer uses that implementation.如果类型
TKey
实现System.IEquatable<T>
泛型接口,则默认的相等比较器使用该实现。
However from what I see of using the dictionary indexer Dictionary<T>[]
, it still relies on overriding GetHashcode eg public override int GetHashCode()
然而,从我所看到的使用字典索引器
Dictionary<T>[]
,它仍然依赖于重写GetHashcode,例如public override int GetHashCode()
I can see that there are recommendations to override the lot for consistency, but I'm trying to understand it more. 我可以看到有建议覆盖该批次的一致性,但我试图更多地理解它。 Is it because IEquatable should instead be directly on MyClass rather than in IMyClass?
是因为IEquatable应该直接在MyClass上而不是在IMyClass中吗? But I'd prefer it on the IMyClass so implementers need to be a dictionary key.
但我更喜欢它在IMyClass上,所以实现者需要成为字典键。
I'm experimenting with IEqualityComparer, but from what I understand I don't need it. 我正在尝试IEqualityComparer,但据我所知,我不需要它。
Dictionary
always checks GetHashCode
first, than goes forward to look into the elements of the bucket Dictionary
总是首先检查GetHashCode
,然后继续查看存储桶的元素
Assume Dictionary
as an Array
with length L, on new element addition it calculates the appropriate index like 假设
Dictionary
为长度为L的Array
,在新元素添加时,它会计算出适当的索引
index = item.GetHashCode() % L
and put that element to the end of the appropriate bucket (just a model, in real word it also takes Abs, and re-build an array if necessary) 并将该元素放在适当的桶的末尾(只是一个模型,实际上它也需要Abs,并在必要时重新构建一个数组)
So in any point it have the following structure 所以在任何一点上它都有以下结构
---
0 -> Item1, Item2
---
1 -> Item3
---
2
---
...
---
L-1-> Item7
On lookup, dictionary calculates index again, and uses Equality to check only bucket elements of calculated index. 在查找时,字典再次计算索引,并使用Equality仅检查计算索引的存储区元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.