How to get MethodInfo of interface method, having implementing MethodInfo of class method?

ぐ巨炮叔叔 提交于 2019-11-26 12:46:53

问题


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.

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?


回答1:


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];


来源:https://stackoverflow.com/questions/1113635/how-to-get-methodinfo-of-interface-method-having-implementing-methodinfo-of-cla

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!