[英]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. 我有类方法的MethodInfo
,它是该类实现的接口定义的一部分。
How can I retrieve the matching MethodInfo
object of the method on the interface type that the class implements ? 如何在类实现的接口类型上检索方法的匹配MethodInfo
对象?
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);
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 如果你想从类实现的接口中找到Method,那么这样的东西应该可行
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.