简体   繁体   中英

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. 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

Have a look at impromptuinterface project and its late binding features.

Specifically InvokeMember and InvokeMemberAction methods. Those are 2x to 4x faster than reflection.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM