关于 IEqualityComparer,有没有理由说明为什么 Equals(T x, T y)
实现应该是我下面所列的以外的任何东西?
public class MyEquality : IEqualityComparer<MyType>
{
//My Equals(T x, T y) always looks like this
public bool Equals(MyType x, MyType y)
{
return this.GetHashCode(x).Equals(this.GetHashCode(y));
}
public int GetHashCode(MyType obj)
{
//assume MyType has a non-nullable member called ID
return obj.ID.GetHashCode();
}
}
最佳答案
是的。哈希码可能会发生冲突,事实上,它们会与许多类型发生冲突。它们的存在只是为了确保哈希表中的值均匀分布,它们对于确定值的相等性没有用。 Eric Lippert对此也有看法(和 another one ):
It is a really bad idea to use 32 bit hash codes as “unique” identifiers. Hash values aren't random per se, but if they're well-distributed then they might as well be for our purposes. You might think “well, sure, obviously they are not truly unique since there are more than four billion possible values, but only four billion hash codes available. But there are so many possible hash values, odds are really good that I’m going to get unique values for my hashes”. But are the chances really that good? 9300 objects is not that many and 1% is a pretty high probability of collision.
也就是说,如果您的 ID 是您在确定相等性时唯一关心的事情,那么比较该 ID 就足够了。但不是它的哈希码,因为哈希码只说
a.GetHashCode() ≠ b.GetHashCode() → a ≠ b
请注意,哈希码相同的情况没有说明。
关于c# - 我应该如何实现 IEqualityComparer<T>.Equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064419/