如何在重写 GetHashCode() 的类型上使用 Object.GetHashCode()
我有一个实现 IEquatable<> 的类 A,使用其字段(例如 Ab 和 Ac)来实现/覆盖 Equals() 和覆盖 GetHashCode(),并且 99% 的时间一切正常。类 A 是继承自接口 D 的层次结构(类 B、C)的一部分;它们都可以一起存储在字典 Dictionary 中,因此当它们都带有自己的默认 Equals()/GetHashCode() 时会很方便。
然而,在构建AI时有时需要做一些工作来获取Ab和Ac的值;当发生这种情况时,我想存储对正在构建的实例的引用。在这种情况下,我不想使用 A 提供的默认 Equals()/GetHashCode() 覆盖。因此,我正在考虑实现一个 ReferenceEqualityComparer,这意味着强制使用 Object 的 Equals()/GetHashCode() :
private class ReferenceEqualityComparer<T> : IEqualityComparer<T>
{
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
return System.Object.ReferenceEquals(x, y);
}
public int GetHashCode(T obj)
{
// what goes here? I want to do something like System.Object.GetHashCode(obj);
}
#endregion
}
问题是,由于 A 重写了 Object.GetHashCode(),我如何(在 A 之外)为 A 的实例调用 Object.GetHashCode() ?
当然,一种方法是 A 不实现 IEquatable<> 。并始终提供 IEqualityComparer<>我创建的任何字典,但我希望得到不同的答案。
谢谢
I have a class A that implements IEquatable<>, using its fields (say, A.b and A.c) for implementing/overriding Equals() and overriding GetHashCode(), and everything works fine, 99% of the time. Class A is part of a hierarchy (class B, C) that all inherit from interface D; they can all be stored together in a dictionary Dictionary, thus it's convenient when they all carry their own default Equals()/GetHashCode().
However, while constructing A I sometime need to do some work to get the values for A.b and A.c; while that's happening, I want to store a reference to the instance that's being built. In that case, I don't want to use the default Equals()/GetHashCode() overrides provided by A. Thus, I was thinking of implementing a ReferenceEqualityComparer, that's meant to force the use of Object's Equals()/GetHashCode():
private class ReferenceEqualityComparer<T> : IEqualityComparer<T>
{
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
return System.Object.ReferenceEquals(x, y);
}
public int GetHashCode(T obj)
{
// what goes here? I want to do something like System.Object.GetHashCode(obj);
}
#endregion
}
The question is, since A overrides Object.GetHashCode(), how can I (outside of A) call Object.GetHashCode() for an instance of A?
One way of course would be for A to not implement IEquatable<> and always supply an IEqualityComparer<> to any dictionary that I create, but I'm hoping for a different answer.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
object.ReferenceEquals
的自然匹配是RuntimeHelpers.GetHashCode
。有关完整详细信息和
ObjectReferenceEqualityComparer
的实现,请参阅此问题的答案:使用ReferenceEquals
的内置IEqualityComparer
The natural match for
object.ReferenceEquals
isRuntimeHelpers.GetHashCode
.See the answer to this question for full details and an implementation of
ObjectReferenceEqualityComparer<T>
: Built-inIEqualityComparer<T>
that usesReferenceEquals
通过互操作调用 CLR 的基本实现:Object.GetHashCode() 的默认实现
Call the CLR's base implementation via interop: Default implementation for Object.GetHashCode()