Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MethodInfo Equality for Declaring Type

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.

like image 826
Jeff Avatar asked Nov 12 '10 19:11

Jeff


3 Answers

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;
}
like image 78
Jeff Avatar answered Oct 24 '22 10:10

Jeff


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.

like image 45
Patrick Huizinga Avatar answered Oct 24 '22 10:10

Patrick Huizinga


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;
    }
like image 44
Ali Yousefi Avatar answered Oct 24 '22 09:10

Ali Yousefi