As a follow up of my question here, I am trying to create an anonymous event handler of which the parameters are decided at run time.
private void RegisterEventHandlers(Control ctl)
{
foreach (Command command in CommandList)
{
EventInfo eventInfo = ctl.GetType().GetEvent(command.Name);
List<ParameterExpression> callArguments = new List<ParameterExpression>();
foreach (ParameterInfo parameter in eventInfo.EventHandlerType.GetMethod("Invoke").GetParameters())
{
callArguments.Add(Expression.Parameter(parameter.ParameterType, parameter.Name));
}
//begin pseudo code
method = (callArguments) =>
{
if (sender != null) ...
if (e != null) ...
name = command.name;
};
or
method = new delegate
{
if (sender != null) ...
if (e != null) ...
name = command.name;
};
//end pseudo code
var body = Expression.Call(Expression.Constant(this), method, callArguments);
var lambda = Expression.Lambda(eventInfo.EventHandlerType, body, callArguments);
eventInfo.AddEventHandler(ctl, lambda.Compile());
}
}
I find my knowledge of lambda expressions and delegates too much lacking to solve this problem...
The anonymous handler has to do nothing more than forward the sender object, event args and command object to another function. Not all events have the same arguments, thus I had the idea to define the handler as an anonymous function with dynamic arguments.
However, other solutions that might tackle my problem are most welcome.