2008年7月29日

假设你有一个类型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];


posted @ 2008-07-29 20:55 Easy Company 阅读(976) 评论(0) 编辑

导航

公告

本人在此发表的文章中可能存在错误,请各位指正,在此表示谢意。但不要因为看法不同而进行人身攻击,毕竟我没有从你那里得到什么,你也没有失去什么。  计数器(2006/10/30起). Add to Google
昵称:Easy Company
园龄:6年9个月
粉丝:0
关注:0

常用链接

我的标签

随笔分类

随笔档案

文章分类

.Net site

Custom Control

MSDN

SourceForge.Net

The Code Project

推荐

最新评论

阅读排行榜

推荐排行榜