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 ?
How to get MethodInfo of interface, if i have MethodInfo of inherited class type?
Asked Answered
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);
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
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();
I think there might be a problem with this solution, since you might have multiple overloads to the method that have the same
Name
–
Puree 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.