1

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.

Community
  • 1
  • 1
David K
  • 333
  • 2
  • 12
  • Here's a related link, just to give yourself some idea of what you're getting yourself into: http://stackoverflow.com/questions/12865848/general-purpose-fromevent-method – Servy Mar 18 '13 at 13:59
  • Interesting example but hell for the maintenance. Thanks for sharing :) – David K Mar 29 '13 at 12:04

1 Answers1

0

You can declare the delegate/lambda as taking a params array:

method = delegate(params object[] args)
{
    ...
};

And inside it, use the MethodInfo class to get information about the method to which the arguments should be forwarded.

But I think you are going too dynamic here. Reflection allows you to bypass the normal abstraction mechanisms that are required when you use compile-time features. This leads to complexity, loss of readability, and it turns a lot of compile-time errors into runtime errors. You can still decide stuff at runtime using polymorphism and delegates, while retaining readability and compile-time type-safety. Microsoft does this all over their libraries. You never see a library that requires the use of reflection, except in the actual implementation of the System.Reflection namespace.

user1610015
  • 6,561
  • 2
  • 15
  • 18
  • I decided in the end that I did not need this. Settling for the sender, EventArgs pattern was good enough. Thanks – David K Mar 29 '13 at 13:14