GetHashCode 用于保存字符串字段的类型

rus*_*Bay 1 c# equality gethashcode

我有这个类,在那里我覆盖了 Object Equals:

public class Foo
{
    public string string1 { get; set; }

    public string string2 { get; set; }

    public string string3 { get; set; }

    public override bool Equals(object other)
    {
        if (!(other is Foo)) return false;
        Foo otherFoo = (other as Foo);

        return otherFoo.string1 == string1 && otherFoo.string2 == string2 && otherFoo.string3 == string3;
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个警告“覆盖 object.equals 但不覆盖 object.gethashcode”,我理解覆盖 GetHashCode 的必要性,以便我的类型根据可散列类型进行操作。

据我研究,为了使此代码唯一,通常使用 XOR 运算符,或者涉及素数乘法。所以,根据我的消息来源,来源1源2我正在考虑我的GesHashCode覆盖方法这两个选项。

1:

public override int GetHashCode() {
        return string1.GetHashCode() ^ string2.GetHashCode() ^ string3.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

2:

public override int GetHashCode() {
        return (string1 + string2 + string3).GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

我也不确定这种方法是否确保了在我的情况下 GetHashCode 覆盖的目的,即消除编译警告,顺便确保类型可以在集合中正确处理,我相信这是如果它们持有的值相等被认为是相等的,但是如果在集合中不同实例上出现相等的值,则需要相应地找到每个实例。

在这两种方法都有效的情况下,我想知道哪一种可能更好以及为什么。

Mat*_*son 5

有一个相当简单但有效的方法来做到这一点:

public override int GetHashCode()
{
    unchecked // Hash code calculation can overflow.
    {
        int hash = 17;

        hash = hash * 23 + firstItem.GetHashCode();
        hash = hash * 23 + secondItem.GetHashCode();

        // ...and so on for each item.

        return hash;
    }
}
Run Code Online (Sandbox Code Playgroud)

其中firstItemsecondItem等等是对哈希码有贡献的项目。(也可以使用更大的素数代替 17 和 23,但实际上并没有太大区别。)

但是请注意,如果您使用的是 .Net Core 3.1,则可以改为执行以下操作

public override int GetHashCode() => HashCode.Combine(firstItem, secondItem, ...etc);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,如果有人想看看的实现HashCode.Combine(),就在这里

它比我发布的代码复杂得多。:)

  • 那些“神奇数字”“17”和“23”是素数;使用素数有助于使哈希分布更均匀。默认设置(我认为?)是,如果达到“int.MaxValue”,它会自动回绕。如果您想明确声明这一点,可以将此逻辑包装在 `unchecked { /* 这里的逻辑 */ }` 中。 (2认同)
  • @RustyBucketBay 不,因为 CPU 上的算术单元不关心数字有多大——无论如何,它需要相同数量的周期。 (2认同)