Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a delegate to a target with variable number of arguments

Let's assume there is a method which takes a variable number of arguments:

void Target( params object[] args );

To attach this to an action with a concrete parameter list we can create a lambda expression:

Action<int, int> someAction += (a, b) => Target(a, b);

Is there a possibility to create this lambda expression dynamically to be able to attach the handler to any type of event? Something like:

someAction += CreateDelegate( typeof(someAction), Target );

I tried to use Delegate.CreateDelegate but it expects the target to provide a method with the concrete list of arguments. I have the feeling it should be possible with Expression.Lambda but for now I didn't have any success. Do you have an Idea?

Edit

Renamed event to action and handler to target.

like image 998
Michael Matejko Avatar asked Oct 22 '12 16:10

Michael Matejko


1 Answers

A delegate for this method:

void Handle( params object[] args );

Would be Action<object[]>, as delegates can not use the params modifier. You would have to do what the compiler does, and map the other method into an object array.

The params keyword is handled by the compiler, so the runtime will use the method as if it just takes a normal object array. In order to do this, you'd have to build an object array of the appropriate list, populate it with your objects, and then attach the method that does that to your handler.

like image 84
Reed Copsey Avatar answered Oct 10 '22 22:10

Reed Copsey