问题
I am adding dynamically controls to page by using LoadControl and Controls.Add. I need somehow to wrap Init and Load event handlers of this loaded controls into my code. So it should be such order of events SomeMyCode() -> Control.Init() -> AnotherMyCode() and the same for Load SomeMyCode() -> Control.Load() -> AnotherMyCode().
My idea was to Get List of Control's event handlers for Init and Load events and add first and last event handers with code I should to run. But I cannot figure out how to do this.
回答1:
You cannot forcibly inject an event handler in front of other handlers already subscribed to an event. If you need method A to be called first, then you'll need to subscribe A first.
Re your comment, that is incredibly hacky. First, you can't even rely on an event having a delegate-field backer; it can be an EventHandlerList
or other - which don't nevessarily expose handy hooks short of reversing the removal.
Second (and more important), it breaks every rule of encapsulation.
In general, if you want to be first, the best approach is to override the OnFoo()
method. The second-best is to subscribe first.
回答2:
Here is a draft of a working solution:
protected void Page_Load(object sender, EventArgs e)
{
Control ctrl = this.LoadControl("WebUserControl1.ascx");
PropertyInfo propertyInfo = typeof(Control).GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
EventHandlerList eventHandlerList = propertyInfo.GetValue(ctrl, new object[]{}) as EventHandlerList;
FieldInfo fieldInfo = typeof(Control).GetField("EventLoad", BindingFlags.NonPublic | BindingFlags.Static);
if(fieldInfo == null)
return;
object eventKey = fieldInfo.GetValue(ctrl);
Delegate eventHandler = eventHandlerList[eventKey] as Delegate;
foreach(EventHandler item in eventHandler.GetInvocationList()) {
ctrl.Load -= item;
}
ctrl.Load += ctrl_Load;
foreach (EventHandler item in eventHandler.GetInvocationList()){
ctrl.Load += item;
}
ctrl.Load += ctrl_Load;
this.Controls.Add(ctrl);
}
void ctrl_Load(object sender, EventArgs e)
{
//throw new NotImplementedException();
}
}
来源:https://stackoverflow.com/questions/372780/adding-event-handlers-by-using-reflection