是否可以为匹配多对多的比较器编写哈希码函数?

Aar*_*ide 7 c# iequalitycomparer

我可以为以下比较器逻辑编写哈希码函数吗?

My如果来自(A,B,C)的至少两个属性匹配,则两个实例相等.

Equals部分很简单,但是我对哈希码部分感到困惑,我的一部分认为它可能是不可能的.

class MyOtherComparer : IEqualityComparer<My>
{
    public bool Equals(My x, My y)
    {
        if (Object.ReferenceEquals(x, y)) 
            return true;      

        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) 
            return false;

        int matches = 0;

        if(x.A == y.A) matches++;

        if(x.B == y.B) matches++;

        if(x.C == y.C) matches++;

        // match on two out of three
        return  (matches > 1)
    }

    // If Equals() returns true for a pair of objects 
    // then GetHashCode() must return the same value for these objects.
    public int GetHashCode(My x)
    {
       // ???
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:除了Reed Copsey的正确答案之外,Ethan Brown清楚地说明了关于模糊比较器一般有用性的一个非常重要的观点 - 请参阅他的答案,以便充分理解本问题/答案的基础.

Ree*_*sey 5

是的,这是可能的.最简单的实现是始终返回常量.

public int GetHashCode(My x) 
{ 
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

GetHashCode的文档状态:

需要实现以确保如果Equals方法对于两个对象x和y返回true,则x的GetHashCode方法返回的值必须等于为y返回的值.

但是,您可以完全自由地为两个不相等的对象返回相同的哈希码.

话虽这么说,这可能会导致一些算法执行得非常糟糕,因为你会得到很多哈希冲突.但是,鉴于您的奇/唯一等式检查的性质,这可能是必需的.


请注意,这在任何情况下都会有问题.根据你的逻辑,可以有三个对象,where comparer.Equals(foo, bar)==truecomparer.Equals(foo, baz)==truebut comparer.Equals(baz, bar)==false.在许多使用的情况下,这可能是有问题的IEqualityComparer<T>.