[英]Method for executing methods with any signature
Is there any possibility to implement a method which to take as parameters a method name and the set of arguments for the method call, to execute the method and return the return value obtained from the method execution? 是否有可能实现一种方法,该方法以方法名称和方法调用的参数集为参数,执行该方法并返回从该方法执行获得的返回值?
This method should be used for calling methods with any number and types of parameters, and any return type. 此方法应用于调用具有任何数量和类型的参数以及任何返回类型的方法。
I know that this can be made using reflection but I am interested if there exist a different approach for this, that would have a smaller effect on the performance than using reflection. 我知道可以使用反射来做到这一点,但是我很感兴趣是否有其他方法可以解决此问题,这对性能的影响比使用反射要小。
Later edit: I need to implement a method like this because I have a class with many different methods with different method signatures, but the wast majority of them are of the same format: 以后的编辑:我需要实现这样的方法,因为我有一个类,其中包含许多具有不同方法签名的不同方法,但是它们绝大部分都是相同格式的:
{
//code block 1
}
using (SomeObject obj = InitializeObject(){
...
//some operations
...
}
{
//code block 2
}
were code block 1 and code block 2 are identical, and only the part in the using block is different. 代码块1和代码块2是相同的,只是using块中的部分不同。 I would like to use only one method that would contain the common blocks of code and to call different methods for the parts that differ from one method to another.
我只想使用一个包含通用代码块的方法,并针对一个方法与另一个方法不同的部分调用不同的方法。 I tried using reflection but it slows down the application in a visible manner so I would not use it.
我尝试使用反射,但是它以可见的方式减慢了应用程序的速度,因此我不会使用它。
抱歉,但是如果您将方法名称获取为字符串-> .net反射,则是一种方法。
没有时间研究细节,但是结合使用System.Reflection和Delegate.DynamicInvoke可能会让您有所了解。
You can leverage latest DLR capabilities in .NET 4.0 您可以利用.NET 4.0中的最新DLR功能
Have a look at impromptuinterface project and its late binding features. 看一下即兴接口项目及其后期绑定功能。
Specifically InvokeMember
and InvokeMemberAction
methods. 特别是
InvokeMember
和InvokeMemberAction
方法。 Those are 2x to 4x faster than reflection. 它们比反射快2到4倍。
Something like this should work... 这样的事情应该起作用...
public static string ExecMethodByName
(string typeName, string methodName, string stringParam)
{
Type t = Type.GetType(typeName);
String s = (String)t.InvokeMember(
methodName,
BindingFlags.InvokeMethod | BindingFlags.Public |
BindingFlags.Static,
null,
null,
new Object[] { stringParam });
return s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.