Generate hash code based on object identity in .net
How can I generate a hash code for an object based on its identity.
What I mean is that:
- if
object.ReferenceEquals(a, b) == true
, thena
andb
will get the same hash code. - if
object.ReferenceEquals(a, b) == false
, thena
andb
should have a decent chan开发者_Python百科ce to get different hash codes even if they are memberwise equal.
What I have is:
class SomeClassThatMakesSenseToCompareByReferenceAndByValue {
override Equals(object o) {
return MemberwiseEquals(o);
}
override GetHashCode() {
return MemberwiseGetHashCode();
}
}
class SomeClassThatNeedsReferenceComparison {
SomeClassThatMakesSenseToCompareByReferenceAndByValue obj;
override Equals(object o) {
return o is SomeClassThatNeedsReferenceComparison && object.ReferenceEquals(this.obj, (o as SomeClassThatNeedsReferenceComparison).obj);
}
override GetHashCode() {
return ?????
}
}
You are probably looking for RuntimeHelpers.GetHashCode
if you don't override GetHashCode
it will return that identic hash code.
Don't do anything - since both objects point to the same instance the same HashCode will always be generated for both objects using the default implementation.
精彩评论