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

标签 c# .net overriding

什么时候应该做以下事情?

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
    }
}

最佳答案

覆盖而不是附加委托(delegate)将产生更高效的代码,因此通常建议您始终尽可能这样做。有关详细信息,请参阅 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# - 什么时候应该覆盖 OnEvent 而不是在继承时订阅事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/159317/

相关文章:

c# - 如何在运行时在安装程序类中获取路径 'C:\inetpub\wwwroot\wss\VirtualDirectories' (c#)

c# - 如何在菜单中按返回后继续游戏

c++ - F# 代码优化还是真的那么慢?

.Net Windows 服务 : install from referenced assembly

.net - 将资源附加到 .resx 文件

c# - 派生类中存在重写和隐藏方法。为什么?

c# - 如何在 C# 中使用比较将列表 <> 复制到另一个列表 <>

c# - 检查枚举是否已过时

ruby-on-rails - Rails + Zurb - 如何确定 CSS 的优先级

delphi - 如何隐藏对象的 protected 过程?