开发者

Generate hash code based on object identity in .net

开发者 https://www.devze.com 2023-01-12 12:56 出处:网络
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, then a and b will get the same hash code.

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, then a and b will get the same hash code.
  • if object.ReferenceEquals(a, b) == false, then a and b 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消