How do I get the MethodInfo of an interface if I have a MethodInfo of an inherited class type?

I have a MethodInfo

class method method that is part of the definition of an interface that this class implements.
How can I get the corresponding MethodInfo

method object for the interface type that the class implements?

+3


source to share


3 answers


I think I found a better way to do this:



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

      

+3


source


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


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







All Articles