.GetHashCode() 是否应该为内存中具有不同引用的两个对象返回相同的值?
我需要重写我的一种类型的 Equals() 方法,但似乎我还必须重写 GetHashCode() 方法。
我不确定:
如果我有 Animal 类型,并且我有 2 个 Animal 实例,它们基本上是相同(相等)的 Cats;例如:
Animal cat_01 = new Animal("Kitty", "Pink");
Animal cat_02 = new Animal("Kitty", "Pink");
我是否应该实现 GetHashedCode() 来为 cas_01 和 cat_02 保留相同的值,即使它们代表内存中的不同引用?
这是 GetHashCode() 应该工作的方式吗?
谢谢
I need to override Equals() method for one of my types but it seems I have to also override GetHashCode() method.
I am not sure:
If I have type Animal and if I have 2 instances of Animal which are basically the same(equal)Cats; like:
Animal cat_01 = new Animal("Kitty", "Pink");
Animal cat_02 = new Animal("Kitty", "Pink");
Should I implement the GetHashedCode() to retirn same value for both cas_01 and cat_02 eventhough they represent different references in the memory?
Is it the way GetHashCode() shuold work?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MSDN 说:
所以是的,GetHashCode 应该为两个实例返回相同的值。
如果您想查看它们是否引用同一个对象,您仍然可以使用 Object.ReferenceEquals。
MSDN says:
So yes, GetHashCode should return the same value for both instances.
You can still use Object.ReferenceEquals if you want to see if they refer to the same object.
我不同意其他答案。这个例子中的动物不是一个值对象,两只猫可以有相同的名字和名称是完全可行的。颜色并且是完全不同的实体。从逻辑上讲,你是说“这只猫和那只猫有相同的名字和相同的颜色,因此它们是同一只猫” - 这不一定是真的。
我建议你做的是将 Animal.Equals 保留为默认实现,并创建一个单独的 IEqualityComparer 实现,如果动物具有相同的名称/颜色,则返回 true。
尝试记住,有许多不同的方法来比较一只猫,并且单一的“等于”方法是不够的:)
I would disagree with the other answers.. Animal in this example is not a value object, it's perfectly feasable that two cats could have the same name & colour and be completely distinct entities. Logically you're saying "this cat and that cat have the same name and the same colour, therefore they are the same cat" - which is not necessarily true..
What I would suggest you do is leave Animal.Equals to the default implementation, and create a seperate IEqualityComparer implementation that returns true if the animals have the same name/colour.
Try to remember that there are many different ways to compare a cat, and one single "Equals" method is not enough :)
根据模型的设计,如果它是值对象(不可变),那么 gethashcode 应该返回所有字段的哈希值,但另一方面,如果它是域实体,那么它应该有一个标识,并且这个标识应该用于比较和gethashcode(两个具有相同名字和年龄的人并不相同,如果你有两只同名的猫并不意味着它们是同一只猫!)。
检查:http://moh-abed.com/2011/ 07/13/实体和值对象/
Depending on the design of the model, if it is value object (immutable) then the gethashcode should return a hashed value of all the fields, but on the other hand if it is a domain entity then it should have an identity and this identity should be used in comparison and gethashcode (two persons with the same name and age are not the same, if you have two cats with the same name that does not mean they are the same cat!).
check: http://moh-abed.com/2011/07/13/entities-and-value-objects/