繁体   English   中英

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

[英]GetHashCode for a type holding string fields

我有这个类,在那里我覆盖了 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;
    }
}

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

据我研究,为了使此代码唯一,通常使用 XOR 运算符,或者涉及素数乘法。 所以,根据我的消息来源, 来源1源2我正在考虑我的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,则可以改为执行以下操作

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM