如何获得接口方法的MethodInfo,有实现类方法的MethodInfo?方法、如何获得、接口、MethodInfo

2023-09-03 03:14:52 作者:恰好心动

我有接口的MethodInto一个方法,实现该接口的类和类型。 我想找到一个实现接口方法的类方法的MethodInfo。

I have a MethodInto of interface method and type of a class that implements the interface. I want to find 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?

推荐答案

OK,我发现了一种方法。

OK, I found a way.

var map = targetType.GetInterfaceMap(interfaceMethod.DeclaringType);
var index = Array.IndexOf(map.InterfaceMethods, interfaceMethod);

if (index == -1)
{
    //something's wrong;
}

return map.TargetMethods[index];