How do I override GetHashCode in a general BaseClass
There's a lot of information on the internet about how to override GetHashCode() when Equals is overriden. But, all these examples are about classes that contain a few fields that can generate a hash. What I'm trying to find is a good GetHashCode implementation for a base class I use for all my business logica layer objects. This class, called BusinessLogica, contains a ToString() implementation, some basic functionality for my framework and the following Equals override:
public override bool Equals(object obj)
{
bool retValue;
if (obj is BusinessLogica && this.GetType() == obj.GetType())
{
retValue = this.ID == ((BusinessLogica)obj).ID;
}
else
{
retValue = false;
}
return retValue;
}
Now, what I've done so far is when I need an object that extends this BusinessLogica and which I use as a key in a dictionary, I override GetHashCode in this particular class and return ID. I could also use this implementation in the BusinessLogica baseclass. Is this 'safe'? I've also seen examples where ToString().GetHashCode() is returned.
What would be wise to use? Or is a GetHashCode on this level not usable and should I rea开发者_如何学运维lly override it in every of my BusinessLogica classes?
Since you only use the ID
property to test for equality then that's almost certainly what you should use to derive your hashcode too.
If ID
is an Int32
then returning this.ID
from the GetHashCode
method should be fine. If ID
is some other type then you could return this.ID.GetHashCode()
instead.
I think the general idea is that - if you have redefined equals, then the following invariant must hold
2 objects that are equal must have the same hashcode. (The other way around may not be true).
Also see this question for an implementation - Why is it important to override GetHashCode when Equals method is overridden?. In your example, however I think you can just use the ID attribute for your hashcode generation.
Assumption: it upholds the above invariant. Also it is immutable, once an object is created, the ID shouldn't change.
Equals(...)
and GetHashCode(...)
should always be implemented equivalently.
If you determine that your objects are equal by their ID
(although that is debatable), then you should also return the HashCode of the ID
.
Since you are using ID to determine if objects are equal your GetHashCode
implementation should be using ID too:
public override int GetHashCode()
{
return this.ID.GetHashCode();
}
The most important thing to always remember when writing an Equals
and GetHashCode
method is that you should never have one without the other and that they agree with eachother. So in this case returning ID
as the hash code (or the hash code of ID
which is the same) is perfectly ok.
精彩评论