[英]GetHashCode Equality
I've wondered about this, so I figure I'll ask it. 我对此感到疑惑,所以我想我会问它。
Most places you'll see use the same semantic logic for overriding Equals as GetHashCode for memberwise equality...however they usually use different implementations: 您将看到的大多数地方使用相同的语义逻辑来覆盖Equals作为成员相等的GetHashCode ...但是它们通常使用不同的实现:
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
var other = (MyType)obj;
if (other.Prop1 != Prop1)
{
return false;
}
return true;
}
public override int GetHashCode()
{
int hash = -657803396;
num ^= Prop1.GetHashCode();
return num;
}
If you're implementing memberwise equality for your type (lets say for storing in a dictionary), why not just override GetHashCode then do something like this for Equals: 如果您正在为您的类型实现成员相等(假设存储在字典中),为什么不重写GetHashCode,然后对Equals执行类似的操作:
public override bool Equals(object obj)
{
return this.HashEqualsAndIsSameType(obj);
}
public static bool HashEquals(this object source, object obj)
{
if (source != null && obj != null)
{
return source.GetHashCode() == obj.GetHashCode();
}
if (source != null || obj != null)
{
return false;
}
return true;
}
public static bool HashEqualsAndIsSameType<T>(this T source, object obj)
{
return (obj == null || obj.GetType() == typeof(T)) && source.HashEquals(obj);
}
Because there is a real risk of conflicts. 因为有冲突的真正危险。 Hash-codes are not unique.
散列码不是唯一的。 They can (when different) prove inequality, but never equality.
他们可以(当不同时)证明不平等,但绝不平等。 When looking for an item:
寻找物品时:
true
they are the same true
它们是相同的 Consider long
... since hash-code is int
, it is easy to see that there are lots and lots of conflicts. 考虑
long
...因为哈希代码是int
,所以很容易看出有很多冲突。
Hashes are not 1-to-1, you can have multiple different values that hash to the same value, but which should compare as not equal. 散列不是1对1,您可以有多个不同的值,这些值散列到相同的值,但应该比较为不相等。 So you cannot really implement Equals in terms of GetHashCode.
所以你无法在GetHashCode方面真正实现Equals。 This is why you have collisions in a hash table, and why a hash table lookup must involve call(s) to both GetHashCode and Equals.
这就是您在哈希表中发生冲突的原因,以及为什么哈希表查找必须涉及对GetHashCode和Equals的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.