使用反射添加事件处理程序 [英] Adding event handlers by using reflection

查看:143
本文介绍了使用反射添加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用LoadControl和Controls.Add将动态控件添加到页面。我需要以某种方式将Init和Load事件处理程序包装在我的代码中。所以它应该是这样的事件的顺序一些SomeMyCode() - > Control.Init() - > AnotherMyCode()和相同的Load SomeMyCode() - > Control.Load() - >另一个MyCode()。_
我的想法是获取控件的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆