假设你有一个类型SomeImplementation,它显示的实现了ISomeInterface接口的方法SomeMethod(),那么如何才能取到这个SomeImplementation.SomeMethod()的MethodInfo呢?
一些程序员使用下面的方法来获取MethodInfo:
MethodInfo mi = typeof(SomeImplementation).GetMethod(
"VBLib.ISomeInterface.SomeMethod",
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
但是有些时候这样做是错误的,它并不能取得方法的MethodInfo。原因是上面代码使用的私有方法的名字是编译器在编译代码时使用的实现细节。C#语言开发的代码可以使用这种方法获取到,但如果是其它语言(如,VB.NET)就不一定能成功了。
试一下对下面的代码,在C#中使用上面的代码看是否能取到MethodInfo。
Public Interface ISomeInterface
Function SomeMethod() As String
End Interface
Public Class SomeImplementation
Implements ISomeInterface
Private Function SomeMethod() As String Implements ISomeInterface.SomeMethod
Return "hello"
End Function
End Class
你会发现对于上面用VB.NET开发的代码,你无法使用前面的代码取到MethodInfo.
正确的方法
下面是取得MethodInfo的正确方法:
MethodInfo imi = typeof(ISomeInterface).GetMethod("SomeMethod");
InterfaceMapping map = typeof(SomeImplementation).GetInterfaceMap(
typeof(ISomeInterface));
int index = Array.IndexOf(map.InterfaceMethods, imi);
MethodInfo result = map.TargetMethods[index];