开发者

how to add a method name from Config file to a delegate?

开发者 https://www.devze.com 2023-01-08 05:33 出处:网络
I have to call a method whose name is coming from a configuration file. I can achieve this using Reflection.MethodInfo.Invoke() method. But my scenario is all these methods should be of same sign开发者

I have to call a method whose name is coming from a configuration file. I can achieve this using Reflection.MethodInfo.Invoke() method. But my scenario is all these methods should be of same sign开发者_Go百科ature. Can i implement it using Delegates? but how can i add a method name stored in configuration file to a delegate?


Look at Delegate.CreateDelegate on MSDN. Some of the best docs there!


You can create a re-usable delegate if you wanted to, e.g. given my type:

public class MyClass
{
    public void DoSomething(string argument1, int argument2)
    {
        Console.WriteLine(argument1);
        Console.WriteLine(argument2);
    }
}

I could do something like:

Action<object, MethodInfo, string, int> action =
    (obj, m, arg1, arg2) => m.Invoke(obj, new object[] { arg1, arg2 });

And call it as:

var method = typeof(MyClass).GetMethod("DoSomething");
var instance = new MyClass();

action(instance, method, "Hello", 24);

If you know your method has a return type, you can do that with a System.Func delegate:

public class MyClass
{        
    public string DoSomething(string argument1, int argument2)
    {
      return string.Format("{0} {1}", argument1, argument2);
    }
}

Func<object, MethodInfo, string, int, string> func =
  (obj, m, arg1, arg2) => (string)m.Invoke(obj, new object[] { arg1, arg2 });

string result = func(instance, method, "Hello", 24);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号