c# - 声明类型的 MethodInfo 相等性

标签 c# .net reflection

我需要检查两个 MethodInfo 之间的相等性。它们实际上是完全相同的 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;
    }

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

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

first.GetMethodBody() == second.GetMethodBody()

谢谢。

最佳答案

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

需要注意的一点:

first.GetMethodBody() == second.GetMethodBody()

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

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;
}

关于c# - 声明类型的 MethodInfo 相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4168489/

相关文章:

c# - 在 Umbraco 的 Razor 中的潜在字符串上使用 string.IsNullOrEmpty

c# - Gridview 分页在添加页面大小时消失

c# - 使用 HTML Agility Pack 抓取元标签和评论

c# - 由于 ReflectionTypeLoadException,无法从程序集中检索 TypeInfo

c# - 使用反射加载外部程序集

c# - 相当于使用 C# SerialPort 类设置 termios c_iflag=IGNPAR

c# - 在 ListView 中更改列

c# - `CallVirt` 和 `New` 关键字

c# - 确定应用程序从哪个位置启动

c# - 如何在 C# 中使用反射调用将字符串数组作为参数的方法