简体   繁体   English

最佳实践:在Component上覆盖OnDispose(bool disposing)vs Disposed事件

[英]Best practice: Override OnDispose(bool disposing) vs Disposed event on Component

In .Net the Component class exposes a Disposed event. 在.Net中, Component类公开Disposed事件。 It also provides a protected member OnDispose(bool disposing) . 它还提供受保护的成员OnDispose(bool disposing)

What is the best practice for a custom component that extends Component ? 扩展Component的自定义组件的最佳实践是什么? Override OnDispose(bool) or attach an event handler to Disposed on construction? 覆盖OnDispose(bool)或将事件处理程序附加到Disposed构造中?

My feeling is that one should override OnDispose(bool) and seal the class. 我的感觉是,应该重写OnDispose(bool)并密封课程。

Thoughts? 思考?

Typically events are used by consumers so that they can be notified when events occur. 通常情况下,消费者使用事件,以便在事件发生时通知他们。 If you're extending the Type and need to clean up resources you should override Dispose(bool disposing) 如果您要扩展Type并需要清理资源,则应覆盖Dispose(bool disposing)

Spence is partly right about the Event handler, multiple events can be assigned but the issue is that you can't guarantee the order in which the Events are handled. Spence对事件处理程序部分正确,可以分配多个事件,但问题是您无法保证处理事件的顺序。

Sealing the class often depends on what you're designing. 密封课程通常取决于你的设计。

The FxCop rule also has some good info: http://msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx FxCop规则也有一些很好的信息: http//msdn.microsoft.com/en-us/library/ms244737(VS.80).aspx

I would recommend overriding the behaviour, as an implementer of your component has access to the event handler and as such could deregister your disposer implementation by accident. 我建议覆盖行为,因为组件的实现者可以访问事件处理程序,因此可能会意外取消注册处理程序实现。 I believe that you may also need to do this depending on what your custom component is doing, as you may need to run your disposing tasks before calling to the base disposer if you have stateful objects or external interfaces etc. 我相信您可能还需要执行此操作,具体取决于您的自定义组件正在执行的操作,因为如果您有状态对象或外部接口等,则在调用基本处理程序之前可能需要运行处理任务。

正如我所听到的那样,这是一个.Net标准,继承者覆盖基类OnXxxxx方法,用户处理Xxxxx事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM