Should .GetHashCode() return same value for two objects having different refences in the memory?
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() t开发者_运维问答o 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
MSDN says:
If two objects compare as equal, the GetHashCode method for each object must return the same value.
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.
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.
public class AnimalNameColorComparer : IEqualityComparer<Animal>
{
public bool Equals(Animal a, Animal b)
{
return a.Name == b.Name &&
a.Color == b.Color
}
public int GetHashCode(Animal a)
{
return a.Name.GetHashCode() ^ a.Color.GetHashCode();
}
}
Try to remember that there are many different ways to compare a cat, and one single "Equals" method is not enough :)
// Create two black cats called fluffy...
var cat1 = new Cat("Fluffy", "Black");
var cat2 = new Cat("Fluffy", "Black");
cat1.Equals(cat2) == false; // they are not the same cat!
var comparer = new AnimalNameColorComparer();
comparer.Equals(cat1, cat2) == true; // But they do have the same name & colour...
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/
精彩评论