根据.net中的对象标识生成哈希码

发布于 2024-09-15 22:45:06 字数 906 浏览 6 评论 0原文

如何根据对象的身份生成对象的哈希码。

我的意思是:

  • 如果 object.ReferenceEquals(a, b) == true,那么 ab 将获得相同的哈希码。
  • 如果 object.ReferenceEquals(a, b) == false,那么 ab 应该有很好的机会获得不同的哈希码,即使他们在成员上是平等的。

我所拥有的是:

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

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

静待花开 2024-09-22 22:45:06

您可能正在寻找 RuntimeHelpers.GetHashCode

You are probably looking for RuntimeHelpers.GetHashCode

晨光如昨 2024-09-22 22:45:06

如果您不重写GetHashCode,它将返回相同的哈希代码。

if you don't override GetHashCode it will return that identic hash code.

在你怀里撒娇 2024-09-22 22:45:06

不要执行任何操作 - 由于两个对象都指向同一个实例,因此将始终使用默认实现为两个对象生成相同的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文