实现了类方法的MethodInfo,如何获取接口方法的MethodInfo? [英] How to get MethodInfo of interface method, having implementing MethodInfo of class method?
问题描述
我有一个接口方法的MethodInfo
和一个实现的类的Type
界面.我想找到实现接口方法的类方法的MethodInfo
.
I have a MethodInfo
of an interface method and Type
of a class that implements the interface.
I want to find the MethodInfo
of the class method that implements the interface method.
简单的method.GetBaseDefinition()
不适用于接口方法.按名称查找也不起作用,因为当显式实现接口方法时,它可以有任何名称(是的,在 C# 中不是).
The simple method.GetBaseDefinition()
does not work with interface methods.
Lookup by name won't work either, because when implementing interface method explicitly it can have any name (yes, not in C#).
那么,涵盖所有可能性的正确方法是什么?
So what is the correct way of doing that that covers all the possibilities?
推荐答案
好的,我找到了一种方法,使用 GetInterfaceMap.
OK, I found a way, using GetInterfaceMap.
var map = targetType.GetInterfaceMap(interfaceMethod.DeclaringType);
var index = Array.IndexOf(map.InterfaceMethods, interfaceMethod);
if (index == -1)
{
//this should literally be impossible
}
return map.TargetMethods[index];
这篇关于实现了类方法的MethodInfo,如何获取接口方法的MethodInfo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!