lundi 18 mai 2015

Create delegate from variadic function with Reflection

In C#, I'd like to be able to subscribe a variadic function (one with the params keyword) to an event. Consider the following code:

void Subscribe(object objectWithEvent, string eventName) {
    EventInfo eventInfo = objectWithEvent.GetType().GetEvent(eventName);
    MethodInfo addMethod = eventInfo.GetAddMethod();
    MethodInfo MethodToInvoke = this.GetType().GetMethod("MyMethod");
    Delegate d = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, MethodToInvoke);
    addMethod.Invoke(objectWithEvent, new object[1]{ d });
}

This code successfully subscribes MyMethod to objectWithEvent.EventName, but only if the event matches the signature of MyMethod exactly. I'd like to be able to subscribe MyMethod to any event, perhaps by declaring MyMethod like so:

public void MyMethod(params object[] parameters)

Simply doing this didn't work, however.

There's also the return type to worry about. Most event handlers return void, so the ability to handle events which return other than void isn't strictly required (though it would be nice).

How can I use reflection, if possible, to subscribe to an event with an arbitrary signature?





Aucun commentaire:

Enregistrer un commentaire