简体   繁体   English

C#事件:覆盖还是注册?

[英]C# events: override or register?

Let's say you have a custom form MyForm : Form and want to run some custom code for the OnLoad event. 假设您有一个自定义表单MyForm : Form并且想为OnLoad事件运行一些自定义代码。

Are there any performance reasons to register for the OnLoad event and run your code in the handler method instead of overriding the OnLoad method in which you call the base method and run your custom code ? 是否有任何性能上的原因要注册OnLoad事件并在处理程序方法中运行代码,而不是覆盖在其中调用基本方法并运行自定义代码的OnLoad方法?

Are there any pros/cons for going one or the other way ? 是否有任何一种利弊? What would you choose and why ? 您会选择什么,为什么?

MSDN page says this: MSDN页面

The OnLoad method also allows derived classes to handle the event without attaching a delegate. OnLoad方法还允许派生类在不附加委托的情况下处理事件。 This is the preferred technique for handling the event in a derived class. 这是在派生类中处理事件的首选技术。

(emphasis mine). (强调我的)。

From performance standpoint, the difference is negligible here. 从性能的角度来看,此处的差异可以忽略不计。 Unless you have millions of subscribers, though. 除非您有数百万的订户。

Overriding the OnLoad method allows you to run code both before and after any other handlers for the event (Which are called by base.OnLoad(e) , or prevent them entirely; this can sometimes be useful. 重写OnLoad方法使您可以在事件的其他任何处理程序之前(之后由base.OnLoad(e)调用,或完全阻止它们base.OnLoad(e)运行代码;这有时很有用。

Also, I believe that it will be a tiny bit faster. 另外,我相信它会更快一点。

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

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