C# .NET GetHashCode function question
Hi I have a class with 6 string properties. A unique object will have different values for a开发者_Python百科tleast one of these fields
To implement IEqualityComparer's GetHashCode function, I am concatenating all 6 properties and calling the GetHashCode on the resultant string.
I had the following doubts:
- Is it necessary to call the GetHashcode on a unique value?
- Will the concatenation operation on the six properties make the comparison slow?
- Should I use some other approach?
If your string fields are named a-f and known not to be null, this is ReSharper's proposal for your GetHashCode()
public override int GetHashCode() {
unchecked {
int result=a.GetHashCode();
result=(result*397)^b.GetHashCode();
result=(result*397)^c.GetHashCode();
result=(result*397)^d.GetHashCode();
result=(result*397)^e.GetHashCode();
result=(result*397)^f.GetHashCode();
return result;
}
}
GetHashCode
does not need to return unequal values for "unequal" objects. It only needs to return equal values for equal objects (it also must return the same value for the lifetime of the object).
This means that:
- If two objects compare as equal with
Equals
, then theirGetHashCode
must return the same value. - If some of the 6 string properties are not strictly read-only, they cannot take part in the
GetHashCode
implementation.
If you cannot satisfy both points at the same time, you should re-evaluate your design because anything else will leave the door open for bugs.
Finally, you could probably make GetHashCode
faster by calling GetHashCode
on each of the 6 strings and then integrating all 6 results in one value using some bitwise operations.
GetHashCode() should return the same hash code for all objects that return true if you call Equals() on those objects. This means, for example, that you can return zero as the hash code regardless of what the field values are. But that would make your object very inefficient when stored in data structures such as hash tables.
Combining the strings is one option, but note that you could for example combine just two of the stringsfor the hash code (while still comparing all the strings in equals!).
You can also combine the hashes of the six separate strings, rather than computing a single hash for a combined string. See for example Quick and Simple Hash Code Combinations
I'm not sure if this will be significantly faster than concatenating the string.
You can use the behavior from:
http://moh-abed.com/2011/07/13/entities-and-value-objects/
精彩评论