正确实施GetHash code正确、GetHash、code

2023-09-03 05:38:58 作者:累却坚持着

我想从社会上听到我应该如何去实现GetHash code(或覆盖​​它)我的对象。我明白我必须这样做,如果我重写equals方法。我已经实现了它的次数相当多,有时只是调用基方法。据我所知,我的对象应等于该对象的另一个实例是否包含相同的细节(成员)。什么是从类的成员获得哈希code的最佳方法是什么?

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?

推荐答案

比方说,您的类看起来是这样的:

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

假设你定义等于让 FROB 的两个实例都是平等的,如果他们的及其酒吧是相等的,但 FooBar的没关系。

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.

这时你应该定​​义 GetHash code 的条款和酒吧。一种方法是这样的:

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

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

基本上,你只是想将所有进入定义平等领域。一种方法是只不断积累就像我已经做了17倍增。它速度快,它的简单,它是正确的,它通​​常给出了一个很好的分配。

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.

 
精彩推荐
图片推荐