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
How to get MethodInfo of interface method, having implementing MethodInfo of class method?
提问by Krzysztof Kozmic
I have a MethodInfo
of an interfacemethod and Type
of a classthat implements the interface.
I want to find the MethodInfo
of 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];