Winforms subscribing to own events

2019-07-03 08:00发布

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.

2条回答
贼婆χ
2楼-- · 2019-07-03 08:22

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.

查看更多
老娘就宠你
3楼-- · 2019-07-03 08:31

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.

查看更多
登录 后发表回答