我在一个类类型上有一个方法的MethodInfo,它是该类实现的接口定义的一部分。
如何在类实现的接口类型上检索方法的匹配MethodInfo对象?
发布于 2013-01-31 16:49:22
我想我找到了最好的方法:
var methodParameterTypes = classMethod.GetParameters().Select(p => p.ParameterType).ToArray();
MethodInfo interfaceMethodInfo = interfaceType.GetMethod(classMethod.Name, methodParameterTypes);发布于 2017-08-04 22:45:52
对于显式实现的接口方法,按名称和参数查找将失败。这段代码应该也能处理这种情况:
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];
}发布于 2013-01-31 16:40:58
如果想要从类实现的接口中查找方法,应该可以使用下面这样的方法
MethodInfo interfaceMethod = typeof(MyClass).GetInterfaces()
.Where(i => i.GetMethod("MethodName") != null)
.Select(m => m.GetMethod("MethodName")).FirstOrDefault();或者,如果您想从类实现的接口中获取方法,您可以这样做。
MethodInfo classMethod = typeof(MyClass).GetMethod("MyMethod");
MethodInfo interfaceMethod = classMethod.DeclaringType.GetInterfaces()
.Where(i => i.GetMethod("MyMethod") != null)
.Select(m => m.GetMethod("MyMethod")).FirstOrDefault();https://stackoverflow.com/questions/14621451
复制相似问题