且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确实施GetHash code

更新时间:2023-01-26 10:27:25

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

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.