How to create a delegate to a target with variable number of arguments
c#, delegates, lambda, linq
Solution
I took a look at the expressions behind the lambda by analyzing following line:
Expression<Action<int, int>> ex = (a, b) => Target(a, b);
Based on this I created an own delegate factory:
public static Delegate CreateDelegate( Type delegateType, Action<object[]> target )
{
var sourceParameters = delegateType.GetMethod("Invoke").GetParameters();
var parameters = sourceParameters.Select( p => Expression.Parameter( p.ParameterType, p.Name ) ).ToArray();
var castParameters = parameters.Select(p => Expression.TypeAs(p, typeof(object))).ToArray();
var createArray = Expression.NewArrayInit(typeof(object), castParameters);
var invokeTarget = Expression.Invoke(Expression.Constant(target), createArray);
var lambdaExpression = Expression.Lambda( delegateType, invokeTarget, parameters);
return lambdaExpression.Compile();
}
Problem
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.