Winforms subscribing to own events

邮差的信 提交于 2019-12-10 22:16:49

问题


One common thing I see developers doing in WinForms is forms/controls subscribing to their own events so you get

this.Load += new System.EventHandler(this.WelcomeQuickViewWF_Load);
this.Activated += new System.EventHandler(this.WelcomeQuickViewWF_Activated);

rather than

protected override void OnActivated(EventArgs e)
{
}

Now I know the second way is more Object Oriented, the first way is event driven and I tend to refactor towards overriding - is there any reason NOT to do this? What I don't want to be doing is making changes that are not really needed and purely an aesthetic choice.


回答1:


By subscribing to your own event, you give up control over when your code is invoked when there are other subscribers to the event. By overriding the event raising method, you have full control over when your code should be invoked. You could invoke it before notifying subscribers or after. There's also no chance of your code being canceled on a cancelable event.

If the method is overridable, do so. Otherwise register as you have no other choice.




回答2:


MSDN says that overriding the On* methods is the preferred technique for handling an event in a derived class:

The OnActivated method also allows derived classes to handle the event without attaching a delegate. Overriding this method is the preferred technique for handling the event in a derived class.

So I'd say the event handler approach is non-idiomatic.



来源:https://stackoverflow.com/questions/10975752/winforms-subscribing-to-own-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!