什么时候应该做以下事情?
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/