当应inheritting在覆盖的OnEvent相对于订阅事件 [英] When should you override OnEvent as opposed to subscribing to the event when inheritting

查看:305
本文介绍了当应inheritting在覆盖的OnEvent相对于订阅事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该什么时候下?

 类Foo:控制
{
    保护覆盖无效的OnClick(EventArgs的发送)
    {
        //新的code在这里
    }
}
 

与此相反?

 类Foo:控制
{
    公共美孚()
    {
        this.Click + =新的EventHandler(点击);
    }

    私人无效点击(对象发件人,EventArgs的)
    {
        // code
    }
}
 

解决方案

覆盖,而不是附加委托将导致更有效的code,所以一般建议你总是这样做在可能的情况。欲了解更多信息,请参阅这个MSDN文章。这里是一个中肯的报价:

  

受保护的OnEventName方法还   允许派生类覆盖   事件不必附加委托   它。派生类必须始终调用   碱的方法的OnEventName   类,以保证注册   委托接收该事件。

When should one do the following?

class Foo : Control
{
    protected override void OnClick(EventArgs e)
    {
        // new code here
    }
}

As opposed to this?

class Foo : Control
{
    public Foo()
    {
        this.Click += new EventHandler(Clicked);
    }

    private void Clicked(object sender, EventArgs e)
    {
        // code
    }
}

解决方案

Overriding rather than attaching a delegate will result in more efficient code, so it is generally recommended that you always do this where possible. For more information see this MSDN article. Here is a pertinent quote:

The protected OnEventName method also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventName method of the base class to ensure that registered delegates receive the event.

这篇关于当应inheritting在覆盖的OnEvent相对于订阅事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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