确定两个方法是否具有相同的基本定义

本文关键字:定义 是否 方法 两个 | 更新日期: 2023-09-27 17:55:33

我刚刚不幸地(至少对于我的应用程序而言)发现在泛型类中声明的两个方法没有相同的基本定义,这在代码中得到了最好的演示:

    public static class Test
    {
        private class Generic<T> { public void Method() { } }
        public static void TestBase()
        {
            var x = typeof(Generic<int>).GetMethod("Method");
            var y = typeof(Generic<double>).GetMethod("Method");
            Debug.Assert(x.GetBaseDefinition() == y.GetBaseDefinition()); // fails
        }
    }

x 和 y.IsGeneric 都是假的,因此不能使用 GetGenericMethodDefinition。

到目前为止,我能想到的唯一解决方案是比较它们的名称,并且它们的声明类型是相同的泛型类型,但在重载的情况下似乎非常脆弱。

所以。。我不认为我在反射库中错过了一个有用的方法可以告诉我这两个方法是否首先在同一类中声明?还是解决方法?

编辑:

为了澄清,我想做一种方法:

    public bool DeclaredInSameClass(MethodInfo a, MethodInfo b);

如果 a 和 b 都首先在同一类中声明,则返回 true。

忽略泛型,这很简单:a.GetBaseDefinition() == y.GetBaseDefinition(),但是如何处理泛型类中声明的方法?

确定两个方法是否具有相同的基本定义

编辑... 最后一次尝试:

    private class Generic<T> { 
        public void Method() { }
        public void Method(string param) { }
        public void OtherMethod() { }  
    }
    private class NonGeneric { public void Method() { } }
    static void Main(string[] args)
    {
        var x = typeof(Generic<int>).GetMethod("Method", new Type[]{});
        var y = typeof(Generic<double>).GetMethod("Method", new Type[]{});
        var a = typeof(Generic<double>).GetMethod("OtherMethod");
        var b = typeof(NonGeneric).GetMethod("Method");
        var c = typeof(Generic<int>).GetMethod("Method", new Type[] { typeof(string) });
        Debug.Assert(DeclaredInSameClass(x, y));
        Debug.Assert(!DeclaredInSameClass(x, a));
        Debug.Assert(!DeclaredInSameClass(x, b));
        Debug.Assert(!DeclaredInSameClass(x, c));
        Debug.Assert(!DeclaredInSameClass(a, b));
    }
    public static bool DeclaredInSameClass(MethodInfo a, MethodInfo b)
    {
        if (a.DeclaringType.IsGenericType != b.DeclaringType.IsGenericType)
        {
            return false;
        }
        else if (a.DeclaringType.IsGenericType)
        {
            var x = a.DeclaringType.GetGenericTypeDefinition().GetMethod(a.Name, a.GetParameters().Select(p => p.ParameterType).ToArray());
            var y = b.DeclaringType.GetGenericTypeDefinition().GetMethod(b.Name, b.GetParameters().Select(p => p.ParameterType).ToArray());
            return x.Equals(y);
        }
        return a.GetBaseDefinition().Equals(b.GetBaseDefinition());
    }