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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With