应该什么时候下?
类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.