如何获取接口的方法信息,如果我有继承类类型的方法信息
本文关键字:信息 方法 继承 类型 何获 取接口 如果 | 更新日期: 2023-09-27 17:56:51
我有一个类类型的方法MethodInfo
,该类类型是该类实现的接口定义的一部分。
如何在类实现的接口类型上检索方法的匹配MethodInfo
对象?
我想
我找到了最好的方法:
var methodParameterTypes = classMethod.GetParameters().Select(p => p.ParameterType).ToArray();
MethodInfo interfaceMethodInfo = interfaceType.GetMethod(classMethod.Name, methodParameterTypes);
对于显式实现的接口方法,按名称和参数查找将失败。此代码也应该处理这种情况:
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];
}
如果你想从类实现的接口中找到方法,这样的东西应该可以工作
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();