views:

42

answers:

2

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 signature. Can i implement it using Delegates? but how can i add a method name stored in configuration file to a delegate?

+1  A: 

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

leppie
+1  A: 

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);
Matthew Abbott
O M G...........
leppie
Nice! Very clear with the examples.
Andy Robinson