mercredi 3 août 2016

Pass extra parameter to event with reflection

I am using reflection to bind events from webcontrols to my own methods. This is a generic function so I don't know the type of control or event in advance, but the events are for instance clicks (button) or selectedIndexChanged (dropdownlist). My function looks like this:

protected void BindEvents(WebControl ctrl, string methodName, string eventType)
{
    System.Reflection.EventInfo eventInfo = ctrl.GetType().GetEvent(eventType);
    Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, methodName);
    eventInfo.AddEventHandler(ctrl, handler);
}

I need to know which event triggered MyEvent by passing in an extra parameter (see below). This is important because every webcontrol can have many events calling MyEvent.

//1. Standard event signature
protected void Test_Click(object sender, EventArgs e) { } 

//2. Signature for my event
protected void MyEvent(object sender, EventArgs e, string eventName) { }

I am not allowed having different signatures when creating the delegate, the code only works when removing the last parameter string eventName. I have tried a workaround by setting eventName as default parameter. I have also tried subclassing EventArgs, but I am not permitted doing any change to the standard signature. I could possibly override the control events to adapt to my signature but I think there must be a simpler way.

Is there any way I can pass this extra parameter to the function when using reflection?





Aucun commentaire:

Enregistrer un commentaire