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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1113635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:33:20  来源:igfitidea点击:

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

c#.netreflectionmethodinfo

提问by Krzysztof Kozmic

I have a MethodInfoof an interfacemethod and Typeof a classthat implements the interface. I want to find the MethodInfoof the class method that implements the interface method.

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

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#).

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

So what is the correctway of doing that that covers all the possibilities?

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

采纳答案by Krzysztof Kozmic

OK, I found a way, using GetInterfaceMap.

好的,我找到了一种方法,使用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];