使用反射来调用方法 [英] using reflection to invoke a method

查看:77
本文介绍了使用反射来调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


有两种方法可以使用反射来调用方法,

1.使用InvokeMember;
2.使用GetType.GetMethod检索MethodInfo对象,然后使用MethodInfo对象调用该方法.我的观点是从结果角度来看,它们是相同的,但是方法2如果需要的话效率更高可以通过同一个MethodInfo对象多次调用该方法-由于每次调用InvokeMember时,都需要查找该方法,方法2中没有保存为MethodInfo对象的任何内容,并且每次InvokeMember进行绑定以查找同一方法时,<我的问题是我的理解观点是否正确,与这两种方法相比是否还有其他区别/优点/缺点. class ="h2_lin">解决方案

对我来说合理的声音.我从不使用InvokeMember.


George_George写道:

我的问题是我的理解点是否正确,并且与这两种方法相比,是否还有其他差异/优点/缺点.



看起来您的理解是正确的.

如果在编译时知道方法签名,则可以通过使用 ^ ]并调用该委托.


Hello everyone,


There are two ways to use reflection to invoke a method,

1. Using InvokeMember;
2. Using GetType.GetMethod to retrieve a MethodInfo object, then use the MethodInfo object to invoke the method.

My point is from the result point of view, they are the same, but method 2 if more efficient if we want to invoke the method multiple of times by the same MethodInfo object -- since each time we call InvokeMember, it needs to find the method, nothing saved as MethodInfo object in method 2 and each time InvokeMember did the binding to find the same method.

My question is whether my point of understanding is correct and whether there any more differences/pros/cons compared with the 2 methods.


thanks in advance,
George

解决方案

Sounds reasonable to me. I never use InvokeMember.


George_George wrote:

My question is whether my point of understanding is correct and whether there any more differences/pros/cons compared with the 2 methods.



Looks like your understanding are correct.

If you know the method signature at compile time, you can gain more performance by creating a delegate from the MethodInfo using Delegate.CreateDelegate(Type, MethodInfo)[^] and invoking that delegate.


这篇关于使用反射来调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆