我需要检查两个 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/