使用反射添加事件处理程序 [英] Adding event handlers by using reflection
问题描述
我的想法是获取控件的Init和Load事件的事件处理程序列表,并添加我应该运行的代码的第一个和最后一个事件处理程序。但是我不知道如何做到这一点。
你不能强制注入一个事件处理程序其他处理程序的前端已经订阅了一个事件。如果您需要首先调用方法A,那么您需要首先订阅A。
重新发表评论,这是非常黑客。首先,你甚至不能依赖一个具有委托领域支持者的事件;它可以是一个 EventHandlerList
或其他 - 它们不会露出方便的钩子,不会反转删除。
第二个(更重要的),它打破了每一个封装规则。
一般来说,如果你想成为第一,最好的方法是覆盖 OnFoo()
方法。第二好的是先订阅。
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.
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.
这篇关于使用反射添加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!