如何获取接口方法的MethodInfo,实现类方法的MethodInfo?

Krz*_*mic 25 .net c# reflection methodinfo

我有MethodInfo一个的接口方法和Type一个的实现了接口.我想找到MethodInfo实现接口方法的类方法.

简单method.GetBaseDefinition()不适用于接口方法.按名称查找也不起作用,因为当显式实现接口方法时,它可以有任何名称(是的,不是在C#中).

那么正确的做法是什么,涵盖所有可能性?

Krz*_*mic 36

好的,我找到了一种方法,使用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];
Run Code Online (Sandbox Code Playgroud)