Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MethodInfo of interface, if i have MethodInfo of inherited class type?

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 ?

like image 947
gillyb Avatar asked Jan 31 '13 08:01

gillyb


2 Answers

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);
like image 105
gillyb Avatar answered Oct 15 '22 05:10

gillyb


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];
}
like image 29
relatively_random Avatar answered Oct 15 '22 06:10

relatively_random