Question

I have the MethodInfo of a method on a class type that is part of an interface definition that that class implements.
How can I retrieve the matching MethodInfo object of the method on the interface type that the class implements ?

Was it helpful?

Solution

I think i found the best way to do this :

var methodParameterTypes = classMethod.GetParameters().Select(p => p.ParameterType).ToArray();
MethodInfo interfaceMethodInfo = interfaceType.GetMethod(classMethod.Name, methodParameterTypes);

OTHER TIPS

Looking up by name and parameters will fail for explicitly implemented interface methods. This code should handle that situation as well:

private static MethodInfo GetInterfaceMethod(Type implementingClass, Type implementedInterface, MethodInfo classMethod)
{
    var map = implementingClass.GetInterfaceMap(implementedInterface);
    var index = Array.IndexOf(map.TargetMethods, classMethod);
    return map.InterfaceMethods[index];
}

If you want to find the Method from the interface that the class implements, something like this should work

MethodInfo interfaceMethod = typeof(MyClass).GetInterfaces()
                .Where(i => i.GetMethod("MethodName") != null)
                .Select(m => m.GetMethod("MethodName")).FirstOrDefault();

Or if you want to get the method from the interface that the class implements from the method info from the class, you can do.

    MethodInfo classMethod = typeof(MyClass).GetMethod("MyMethod");

    MethodInfo interfaceMethod = classMethod.DeclaringType.GetInterfaces()
        .Where(i => i.GetMethod("MyMethod") != null)
        .Select(m => m.GetMethod("MyMethod")).FirstOrDefault();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top