How to use .NET Action to execute a method with unknown number of parameters?
I think you're overthinking things a little bit. So let's start from the top:
A lambda expression is a notation to reference a method execution. Example:
x => x + 3
At the most basic level, this is representing a function that takes 1 input,
x
, and then returns a value equal tox + 3
. So in your situation, your expression:() => DoSomething(15, "Something")
Represents a method taking 0 parameters, and then invoking the method
DoSomething(15, "Something")
. The compiler is behind the scenes translating that into aFunc
orAction
delegate for you. So it is in effect:new Action(delegate(){ DoSomething(15, "Something")});
The compiler rewrite of my simple expression above would be:
new Func<int, int>(delegate(int x){ return x + 3;});
Next up, if you want to invoke an action later, the syntax for doing so is fairly straightforward:
Action someMethod = new Action(() => { Console.WriteLine("hello world"); }));someMethod(); // Invokes the delegate
So if you have a given
Action
instance, simply invoking it with the()
syntax is all you need, sinceAction
is a delegate that takes 0 parameters and returns nothing.A function is similarly easy:
Func<int, int> previousGuy = x => x + 3;var result = previousGuy(3); // result is 6
Lastly, if you want to pass along a method to invoke, and you don't have context for the parameters at that point, you can simply wrap your call in an action and invoke that later. For example:
var myAction = new Action(() => { // Some Complex Logic DoSomething(15, "Something"); // More Complex Logic, etc });InvokeLater(myAction);public void InvokeLater(Action action){ action();}
All of the data is captured in a closure of your method, and thus is saved. So if you can manage to pass along an
Action
to your event with thee.Argument
property, all you would need to do would be to call(e.Argument as Action)()
.
Can't you use DynamicInvoke()
on that delegate (it takes params object[] args
as argument)
action.DynamicInvoke(arg1, arg2, arg3 );