c# - 我应该如何实现 IEqualityComparer<T>.Equals

标签 c# equals gethashcode iequalitycomparer

关于 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() → ab

请注意,哈希码相同的情况没有说明。

关于c# - 我应该如何实现 IEqualityComparer<T>.Equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16064419/

相关文章:

c# - 通过System.Linq在C#中获取元素的属性名称和值

c# - .NET前端、MYSQL后端的打印解决方案

c# - 将字符串转换为 Int(不解析)

java - 为抽象类实现 clone()、equals() 或 hashCode() 是否有意义?

java - 有什么可以警告我不要使用 type.equals(incompatibleType) 吗?

c# - string.GetHashCode() 在调试和发布中返回不同的值,如何避免这种情况?

c# - 等于、GetHashCode、EqualityComparers 和模糊相等

c# - 在外发电子邮件 EWS 中设置回复地址

c# - 如何自定义 ".NET FrameworkInitialization Error"?

java - 比较对象,相同的内容,不同的 id(在 eclipse 调试器中)