正确实现 GetHashCode
我想听听社区关于我应该如何为我的对象实现 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您的类如下所示:
假设您定义了 equals,因此如果
Foo
和Bar
相等,则Frob
的两个实例相等,但 FooBar 并不重要。然后,您应该根据
Foo
和Bar
定义GetHashCode
。一种方法是这样的:基本上,您只想合并定义相等性的所有字段。一种方法是像我一样不断累加并乘以 17。它快速、简单、正确,并且通常能提供良好的分布。
Let's say your class looks like this:
Let's say you define equals so that two instances of
Frob
are equal if theirFoo
and theirBar
are equal, butFooBar
doesn't matter.Then you should define
GetHashCode
in terms ofFoo
andBar
. One way is like this: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.