正确实现 GetHashCode

发布于 2024-12-28 20:45:12 字数 154 浏览 4 评论 0原文

我想听听社区关于我应该如何为我的对象实现 GetHashCode(或覆盖它)的信息。我知道如果我重写 equals 方法,我需要这样做。我已经实现了很多次,有时只是调用基本方法。我知道我的对象应该等于该对象的另一个实例,如果它包含相同的详细信息(成员)。从类成员那里获取哈希码的最佳方法是什么?

I'd like to hear from the community on how I should go about implementing GetHashCode (or override it) for my object. I understand I need to do so if I override the equals method. I have implemented it a fair amount of times, sometimes just calling the base method. I understand that my object should equal another instance of the object if it contains the same details (members). What is the best way to get a hash code from the class's members?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满天都是小星星 2025-01-04 20:45:12

假设您的类如下所示:

class Frob {
    public string Foo { get; set; }
    public int Bar { get; set; }
    public double FooBar { get; set; }
}

假设您定义了 equals,因此如果 FooBar 相等,则 Frob 的两个实例相等,但 FooBar 并不重要。

然后,您应该根据 FooBar 定义 GetHashCode。一种方法是这样的:

return this.Foo.GetHashCode() * 17 + this.Bar.GetHashCode();

基本上,您只想合并定义相等性的所有字段。一种方法是像我一样不断累加并乘以 17。它快速、简单、正确,并且通常能提供良好的分布。

Let's say your class looks like this:

class Frob {
    public string Foo { get; set; }
    public int Bar { get; set; }
    public double FooBar { get; set; }
}

Let's say you define equals so that two instances of Frob are equal if their Foo and their Bar are equal, but FooBar doesn't matter.

Then you should define GetHashCode in terms of Foo and Bar. One way is like this:

return this.Foo.GetHashCode() * 17 + this.Bar.GetHashCode();

Basically, you just want to incorporate all the fields that go into defining the equality. One way is to just keep accumulating and multiplying by 17 like I've done. It's fast, it's simple, it's correct, and it usually gives a good distribution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文