根据.net中的对象标识生成哈希码
如何根据对象的身份生成对象的哈希码。
我的意思是:
- 如果
object.ReferenceEquals(a, b) == true
,那么a
和b
将获得相同的哈希码。 - 如果
object.ReferenceEquals(a, b) == false
,那么a
和b
应该有很好的机会获得不同的哈希码,即使他们在成员上是平等的。
我所拥有的是:
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 ?????
}
}
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 chance 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 ?????
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能正在寻找 RuntimeHelpers.GetHashCode
You are probably looking for RuntimeHelpers.GetHashCode
如果您不重写
GetHashCode
,它将返回相同的哈希代码。if you don't override
GetHashCode
it will return that identic hash code.不要执行任何操作 - 由于两个对象都指向同一个实例,因此将始终使用默认实现为两个对象生成相同的 HashCode。
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.