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

3

7

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 ?

Puree answered 31/1, 2013 at 8:34 Comment(0)
P
4

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);
Puree answered 31/1, 2013 at 8:49 Comment(2)
This assumes that the interface method is mapped to a type of the same name. I don't believe it will work if the method is implemented explicitly.Clere
Typo. I meant: "This assumes that the interface method is mapped to a class method of the same name."Clere
C
3

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];
}
Clere answered 4/8, 2017 at 14:45 Comment(0)
W
0

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();
Wigan answered 31/1, 2013 at 8:40 Comment(3)
I think there might be a problem with this solution, since you might have multiple overloads to the method that have the same NamePuree
you could and any other requirments in the where clause,Wigan
I think i already added a more elegant solution. But thanks for the help! :)Puree

© 2022 - 2024 — McMap. All rights reserved.