C# 正确实现 GetHashCode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9009760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:34:56  来源:igfitidea点击:

Implementing GetHashCode correctly

c#.netequals

提问by Zivka

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?

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

采纳答案by jason

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 Frobare equal if their Fooand their Barare equal, but FooBardoesn't matter.

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

Then you should define GetHashCodein terms of Fooand Bar. One way is like this:

那么你应该GetHashCodeFoo和来定义Bar。一种方法是这样的:

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.

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