加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 什么时候应该覆盖OnEvent而不是在继承时预订事件

发布时间:2020-12-15 18:14:01 所属栏目:百科 来源:网络整理
导读:何时应该做以下事情? class Foo : Control{ protected override void OnClick(EventArgs e) { // new code here }} 与此相反? class Foo : Control{ public Foo() { this.Click += new EventHandler(Clicked); } private void Clicked(object sender,Event
何时应该做以下事情?
class Foo : Control
{
    protected override void OnClick(EventArgs e)
    {
        // new code here
    }
}

与此相反?

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

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

解决方法

覆盖而不是附加代理将导致更有效的代码,因此通常建议您始终尽可能地执行此操作.有关更多信息,请参阅 this MSDN article.这是一个相关报价:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读