Implementing GetHashCode correctly
This question already has an answer here:
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.
链接地址: http://www.djcxy.com/p/39752.html上一篇: 实现GetHashCode
下一篇: 正确实现GetHashCode
