调用无参数构造函数后具有引用类型成员的 c# 结构的相等性和 gethashcode 覆盖

Equality and gethashcode override for c# structs with reference type members after calling parameterless constructor

我正在设计一个结构来比较来自两个不同来源的方法签名(目前使用 System.Reflection 直接从程序集中获取它们)。因为我只关心唯一性,所以我选择 HashSet< MethodSignature> 来存储我的结构并使用子集方法比较它们。

public struct MethodSignature : IEquatable<MethodSignature>
{
    #region Immutable fields
    public readonly string AssemblyName;
    public readonly string ClassName;
    public readonly string MethodName;
    public readonly System.Type ReturnType;
    public readonly Dictionary<string, System.Type> Parameters;
    #endregion

    #region Constructors
    public MethodSignature(string assemblyName, string className, string methodName, Type returnType, Dictionary<string, System.Type> parameters)
    {
        AssemblyName = assemblyName;
        ClassName = className;
        MethodName = methodName;
        ReturnType = returnType;
        Parameters = parameters;
    }
    #endregion

    #region public Methods
    public override string ToString()
    {
        string paramts = GetParametersAsString();
        return string.Format("{0} {1}::{2}.{3}({4})", ReturnType.ToString(), AssemblyName, ClassName, MethodName, paramts);
    }
    public static bool operator ==(MethodSignature signature1, MethodSignature signature2)
    {
        // No nasty null checking thanks to value types :D :D :D
        return signature1.Equals(signature2);
    }
    public static bool operator !=(MethodSignature signature1, MethodSignature signature2)
    {
        // No nasty null checking thanks to value types :D :D :D
        return !signature1.Equals(signature2);
    }
    public bool Equals(MethodSignature signature)
    {
        return AreMethodSignatureEquals(signature);
    }
    public override bool Equals(object obj)
    {
        if (obj is MethodSignature)
            return Equals((MethodSignature)obj);
        else
            return false;
    }
    #endregion

    #region private Members
    private string GetParametersAsString()
    {
        StringBuilder sb = new StringBuilder();
        foreach (KeyValuePair<string, System.Type> param in Parameters)
        {
            sb.Append(string.Format("{0} {1},", param.Value.ToString(), param.Key.ToString()));
        }

        //Remove trailing comma
        sb.Length--;
        return sb.ToString();
    }

    private bool AreMethodSignatureEquals(MethodSignature signature)
    {
        return (AreAssemblyNamesEqual(signature.AssemblyName)
             && AreClassNameEquals(signature.ClassName)
             && AreMethodNameEquals(signature.MethodName)
             && AreReturnTypeEquals(signature.ReturnType)
             && AreParametersEquals(signature.Parameters));
    }

    private bool AreParametersEquals(Dictionary<string, Type> parameters)
    {
        return parameters.Count == Parameters.Count
            && AreSameSizeDictionariesKeyValuePairsEqual(parameters);
    }

    private bool AreSameSizeDictionariesKeyValuePairsEqual(Dictionary<string, Type> parameters)
    {
        foreach (KeyValuePair<string, Type> param in Parameters)
        {
            Type paramType;

            //TryGetValue returns true if finds the keyValuePair              
            if (parameters.TryGetValue(param.Key, out paramType))
            {
                if (AreParameterTypesDifferent(param.Value, paramType))
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        return true;
    }

    private static bool AreParameterTypesDifferent(Type typeParameter1, Type typeParameter2)
    {
        return !typeParameter2.Equals(typeParameter1);
    }

    private bool AreReturnTypeEquals(Type returnType)
    {
        return returnType.Equals(ReturnType);
    }

    private bool AreMethodNameEquals(string methodName)
    {
        // Ensuring case sensitive using IEquatable<string>
        return methodName.Equals(MethodName);
    }

    private bool AreClassNameEquals(string className)
    {
        // Ensuring case sensitive using IEquatable<string>
        return className.Equals(ClassName);
    }

    private bool AreAssemblyNamesEqual(string assemblyName)
    {
        // Ensuring case sensitive using IEquatable<string>
        return assemblyName.Equals(AssemblyName);
    }
    #endregion
}

我已经检查了 System.Reflection 中类似类型的一些实现,但是,我更喜欢使用自定义结构,因为 Equality 被覆盖了,而且因为 ValueTypes 的默认比较将通过引用字典(因为它应该是引用类型),这不是我的目的。

完整的 Equality 实现已准备就绪并且可以完美运行(已实现 IEquatable< MethodSignature>、覆盖 Object.Equals、重载 ==!=

但是,现在我遇到了 MethodSignature 的一个全零实例,以及它在使用相等时的行为......让我们来看看

MethodSignature ms1 = new MethodSignature();
MethodSignature ms2 = new MethodSignature();

// This will throw null reference exception
bool areEqual = ms1.Equals(ms2);

编译器不会抱怨,因为 ms1ms2 被认为已初始化。我知道这归结为 C# 中的所有值类型在默认情况下都有默认其所有成员的无参数构造函数。如果我将此行为与 Microsoft 提供的值类型

进行比较
        int a = new int();
        int b = new int();

        // Returns true
        Console.WriteLine(a.Equals(b));

当然它们是相等的,比较 GetHashCode() 的 returns returns true

我检查过 this and this too, however, I cannot figure out how to create a default for every reference type for this struct that complies with the GetHashCode concept (Two objects that are equal return hash codes that are equal. taken from Microsoft )

最后我的问题是:

关于在使用默认无参数构造函数时结构中存在引用类型时如何重写符合 IEquatable 实现的 GetHashCode() 的任何想法?

首先检查使用默认构造函数创建的 MethodSignature 个实例是否相等时,由于所有字段都是 null(它们都是引用类型),您将得到异常。 如果你想要

的两个实例
 MethodSignature ms1 = new MethodSignature();
 MethodSignature ms2 = new MethodSignature();

要被视为相等,您应该按如下方式调整代码:

    private bool AreParametersEquals(Dictionary<string, Type> parameters)
    {   
        if((parameters == null) && (Parameters == null)) return true;
        if((parameters == null) || (Parameters == null)) return false;
        if(parameters.Count != Parameters.Count) return false;

        var paramArray1 = parameters.OrderBy(p => p.Key).ToArray();
        var paramArray2 = Parameters.OrderBy(p => p.Key).ToArray();
        for(int i = 0; i < paramArray1.Length; i++)
        {
            if(!string.Equals(paramArray1[i].Key, paramArray2[i].Key)) return false;
            if(!string.Equals(paramArray1[i].Key, paramArray2[i].Key)) return false;
        }
        return true;
    }

    private bool AreReturnTypeEquals(Type returnType)
    {
        if((returnType == null) && (ReturnType == null)) return true;
        return (returnType != null) && returnType.Equals(ReturnType);
    }

    private bool AreMethodNameEquals(string methodName)
    {
        // Ensuring case sensitive using IEquatable<string>
        return string.Equals(methodName, MethodName);
    }

    private bool AreClassNameEquals(string className)
    {
        // Ensuring case sensitive using IEquatable<string>
        return string.Equals(className, ClassName);
    }

    private bool AreAssemblyNamesEqual(string assemblyName)
    {
        // Ensuring case sensitive using IEquatable<string>
        return string.Equals(assemblyName, AssemblyName);

    }

还有一个 GetHashCode 的实现,可以按照您想要的方式运行(基于 Jon Skeet 在 What is the best algorithm for an overridden System.Object.GetHashCode? 中的建议):

public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = (int)2166136261;
            // Suitable nullity checks etc, of course :)
            hash = (hash * 16777619) ^ AssemblyName?.GetHashCode()??0;
            hash = (hash * 16777619) ^ ClassName?.GetHashCode()??0;
            hash = (hash * 16777619) ^ MethodName?.GetHashCode()??0;
            hash = (hash * 16777619) ^ ReturnType?.GetHashCode()??0;
            if(Parameters == null) return hash;
            var paramArray = Parameters.OrderBy(p => p.Key).ToArray();
            for(int i = 0; i < Parameters.Count; i++)
            {
                hash = (hash * 16777619) ^ paramArray[i].Key?.GetHashCode()??0;
                hash = (hash * 16777619) ^ paramArray[i].Value?.GetHashCode()??0;
            }
            return hash;
        }
    }

此实现将使用字段的 null 值,并且 return 对于字段中具有完全相同值的不同实例,结果相同。

注意:一旦使用此哈希码(例如,将 MethodSignature 实例存储在 Dictionary 中),您永远不应更改基础 Parameter Dictionary,因为这会影响 GetHashCode计算。