After some research I found some articles:
It helped me to understand what I was trying to do and I should do.
I need to use Delegate.CreateDelegate
passing the EventHandlerType
(the type of the event, the delegate), a instance of a class and the method info of the method (from the class in the previous parameter) that will handle the event. Target is the control that fires this event.
Delegate handler = Delegate.CreateDelegate(evt.EventHandlerType, abc, mi1, false);
evt.AddEventHandler(target, handler);
Further digging lead me to this method. I can subscribe to events using lambda expression. Using Action<T>
I can subscribe with different types and numbers of parameters.
public static Delegate Create<T>(EventInfo e, Action<T> a)
{
var parameters = e.EventHandlerType.GetMethod("Invoke").GetParameters().Select(p => Expression.Parameter(p.ParameterType, "p")).ToArray();
var exp = Expression.Call(Expression.Constant(a), a.GetType().GetMethod("Invoke"), parameters);
var l = Expression.Lambda(exp, parameters);
return Delegate.CreateDelegate(e.EventHandlerType, l.Compile(), "Invoke", false);
}
Using this method (e is the EventInfo; EventManager is the class with the static method above)
e.AddEventHandler(this, EventManager.Create<int>(e, (x) => Console.WriteLine("Execute")));