GetHashCode Equality

Jef*_*eff 5 .net c# gethashcode

我对此感到疑惑,所以我想我会问它.

您将看到的大多数地方使用相同的语义逻辑来覆盖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;
    }
Run Code Online (Sandbox Code Playgroud)

如果您正在为您的类型实现成员相等(假设存储在字典中),为什么不重写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);
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 10

因为冲突的真正危险.散列码不是唯一的.他们可以(当不同时)证明不平等,但绝不平等.寻找物品时:

  • 获取哈希码
  • 如果哈希码不同,则对象不同; 丢弃它
  • 如果哈希码相同,请检查等于:
  • 如果Equals报告true它们是相同的
  • 否则丢弃

考虑long......因为哈希码是int,很容易看出有很多冲突.