How do I get the MethodInfo of an interface if I have a MethodInfo of an inherited class type?
3 answers
If you want to find a method from an 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 a method from an interface that a class implements from a method information from a 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();
0
source to share
Search by name and parameters will fail for explicitly implemented interface methods. This code should also handle this situation:
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];
}
0
source to share