包含字符串字段的类型的GetHashCode

问题描述

我有这个课程,在这里我重写了对象等于:

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;
    }
}

我得到一个警告“覆盖object.equals,但不覆盖object.gethashcode”,我知道需要覆盖GetHashCode,这样我的类型才能根据可哈希类型运行。

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

1:

public override int GetHashCode() {
        return string1.GetHashCode() ^ string2.GetHashCode() ^ string3.GetHashCode();
}

2:

public override int GetHashCode() {
        return (string1 + string2 + string3).GetHashCode();
}

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

在两种方法都有效的情况下,我想知道哪种方法更好,为什么呢?

解决方法

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

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;
    }
}

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

但是请注意,如果您使用的是.Net Core 3.1,you can do this instead

public override int GetHashCode() => HashCode.Combine(firstItem,secondItem,...etc);

顺便说一句,如果有人想看看the implementation of HashCode.Combine(),it's here

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