If you want to, for example, only use void methods without any arguments as event handlers for events of any type, you can compile expression trees to do that. This can be modified to accomodate other event handler types, but you'll have to map the event handler's parameters to the event's somehow.
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
class EventRaiser
{ public event EventHandler SomethingHappened;
}
class Handler
{ public void HandleEvent() { /* ... */}
}
class EventProxy
{ static public Delegate Create(EventInfo evt, Action d)
{ var handlerType = evt.EventHandlerType;
var eventParams = handlerType.GetMethod("Invoke").GetParameters();
//lambda: (object x0, EventArgs x1) => d()
var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,"x"));
// - assumes void method with no arguments but can be
// changed to accomodate any supplied method
var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod("Invoke"));
var lambda = Expression.Lambda(body,parameters.ToArray());
return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}
}
public static void attachEvent()
{ var raiser = new EventRaiser();
var handler = new Handler();
string eventName = "SomethingHappened";
var eventinfo = raiser.GetType().GetEvent(eventName);
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));
//or even just:
eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine("!")));
}