I need to check equality between two MethodInfos. They are actually the exact same MethodInfo with the exception of the ReflectedType (that is, the DeclaringType is the same and the methods should actually have the same body). There are a number of ways of doing this, but I'm looking for the most efficient.
Right now I have:
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;
}
This is kind of expensive, so I'm wondering if there's a better way...
Should I be comparing the two method bodies instead? eg.
first.GetMethodBody() == second.GetMethodBody()
Thanks.
i guess I'll leave my answer as the answer to the question...
One thing to note:
first.GetMethodBody() == second.GetMethodBody()
does NOT work...so the only answer I've found to date is:
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;
}
Would comparing the MetadataToken and Module help?
The documentation of MetadataToken describes it as: "A value which, in combination with Module, uniquely identifies a metadata element."
So far I've found it to be working for comparing equal-except-for-ReflectedType MemberInfo instances. But I did not test it for cases like generic method definitions.
this code works when you try to equal class and interface method:
static bool EquelMethods(MethodInfo method1, MethodInfo method2)
{
var find = method1.DeclaringType.GetMethod(method2.Name, method2.GetParameters().Select(p => p.ParameterType).ToArray());
return find != null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With