惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
G
Google Developers Blog
有赞技术团队
有赞技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
罗磊的独立博客
博客园 - 聂微东
V
Visual Studio Blog
博客园_首页
D
DataBreaches.Net
腾讯CDC
I
InfoQ
F
Fortinet All Blogs
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 【当耐特】
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
月光博客
月光博客
Recent Announcements
Recent Announcements
MongoDB | Blog
MongoDB | Blog
C
Check Point Blog

博客园 - Easy Company

SQL Server 2008中许多兼容性上的问题 Mock 对象何时使用? ThreadPool 在.Net 2.0 SP1中的部分变化可能会让你的程序停止工作 目前不能使用SQL Server 2008 CTP February 2008存储Team Foundation Server 2008的数据 Javascript操作在各浏览器下的性能比较 WCF Web 编程模型资源 代码行数引起的思考 在按钮点击后禁用它直到操作完成 - Easy Company - 博客园 ASP.NET 2.0中使用强类型访问PreviousPage属性页的控件 Silverlight 与 Microsoft ASP.NET Futures (July 2007) 更新 VS 2008 和.NET 3.5 Beta 2 安装注意事项 Partial Methods CIL(Common Intermediate Language)指令集 刚刚下载了 Visual Studio 2005 Service Pack 1 (SP1) 使用 Facade 设计模式管理 ASP.Net Session 变量 .Net 中的日志 使用 Membership 时获取用户的最后登录时间 How To 推荐用于 AJAX 页面的进度指示器图片
如何取得显示实现方法的MethodInfo
Easy Company · 2008-07-29 · via 博客园 - Easy Company

假设你有一个类型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 InterfacePublic Class SomeImplementation
    
Implements ISomeInterfacePrivate 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];