简体   繁体   English

如何在重写GetHashCode()的类型上使用Object.GetHashCode()

[英]How to use Object.GetHashCode() on a type that overrides GetHashCode()

I have a class A that implements IEquatable<>, using its fields (say, Ab and Ac) for implementing/overriding Equals() and overriding GetHashCode(), and everything works fine, 99% of the time. 我有一个实现IEquatable <>的类A,使用它的字段(例如,Ab和Ac)来实现/重写Equals()并覆盖GetHashCode(),并且99%的时候一切正常。 Class A is part of a hierarchy (class B, C) that all inherit from interface D; A类是层次结构(B类,C类)的一部分,它们都从接口D继承; they can all be stored together in a dictionary Dictionary, thus it's convenient when they all carry their own default Equals()/GetHashCode(). 它们都可以一起存储在字典中,因此当它们都带有自己的默认Equals()/ GetHashCode()时很方便。

However, while constructing AI sometime need to do some work to get the values for Ab and Ac; 然而,在构建AI时,有时需要做一些工作来获得Ab和Ac的值; 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(): 在这种情况下,我不想使用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
    }

The question is, since A overrides Object.GetHashCode(), how can I (outside of A) call Object.GetHashCode() for an instance of A? 问题是,由于A重写了Object.GetHashCode(),我怎样才能(在A之外)为A的实例调用Object.GetHashCode()?

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. 一种方法当然是A不能实现IEquatable <>并且总是向我创建的任何字典提供IEqualityComparer <>,但我希望得到不同的答案。

Thanks 谢谢

The natural match for object.ReferenceEquals is RuntimeHelpers.GetHashCode . 对于自然匹配object.ReferenceEqualsRuntimeHelpers.GetHashCode

See the answer to this question for full details and an implementation of ObjectReferenceEqualityComparer<T> : Built-in IEqualityComparer<T> that uses ReferenceEquals 有关完整详细信息和ObjectReferenceEqualityComparer<T>的实现,请参阅此问题的答案: 使用ReferenceEquals内置IEqualityComparer<T>

通过interop调用CLR的基本实现: Object.GetHashCode()的默认实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM