MethodInfo声明类型的等式

Jef*_*eff 10 .net c# reflection

我需要检查两个MethodInfos之间的相等性.它们实际上是完全相同的MethodInfo,但ReflectedType除外(也就是说,DeclaringType是相同的,并且方法实际上应该具有相同的主体).有很多方法可以做到这一点,但我正在寻找最有效的方法.

现在我有:

    public static bool AreMethodsEqualForDeclaringType(this MethodInfo first, MethodInfo second)
    {
        first = first.ReflectedType == first.DeclaringType ? first : first.DeclaringType.GetMethod(first.Name, first.GetParameters().Select(p => p.ParameterType).ToArray());
        second = second.ReflectedType == second.DeclaringType ? second : second.DeclaringType.GetMethod(second.Name, second.GetParameters().Select(p => p.ParameterType).ToArray());
        return first == second;
    }
Run Code Online (Sandbox Code Playgroud)

这有点贵,所以我想知道是否有更好的方法......

我应该比较两个方法体吗?例如.

first.GetMethodBody() == second.GetMethodBody()
Run Code Online (Sandbox Code Playgroud)

谢谢.

Jef*_*eff 4

我想我会留下我的答案作为问题的答案......

需要注意一件事:

first.GetMethodBody() == second.GetMethodBody()
Run Code Online (Sandbox Code Playgroud)

不起作用...所以我迄今为止找到的唯一答案是:

public static bool AreMethodsEqualForDeclaringType(this MethodInfo first, MethodInfo second)
{
    first = first.ReflectedType == first.DeclaringType ? first : first.DeclaringType.GetMethod(first.Name, first.GetParameters().Select(p => p.ParameterType).ToArray());
    second = second.ReflectedType == second.DeclaringType ? second : second.DeclaringType.GetMethod(second.Name, second.GetParameters().Select(p => p.ParameterType).ToArray());
    return first == second;
}
Run Code Online (Sandbox Code Playgroud)