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

前端之家收集整理的这篇文章主要介绍了c# – 什么时候应该覆盖OnEvent而不是在继承时预订事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
何时应该做以下事情?
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.

猜你在找的C#相关文章