When should you override OnEvent as opposed to subscribing to the event when inheritting

后端 未结 7 1949
梦谈多话
梦谈多话 2020-12-11 01:33

When should one do the following?

class Foo : Control
{
    protected override void OnClick(EventArgs e)
    {
        // new code here
    }
}
7条回答
  •  独厮守ぢ
    2020-12-11 02:19

    Be aware that (at least in .NET 2.0) I have found a few places in the framework (specifically in the DataTable class) where the OnFoo method is only called when the corresponding Foo event has been handled! This contravenes the framework design guidelines but we're stuck with it.

    I've gotten around it by handling the event with a dummy handler somewhere in the class, eg:

    public class MyDataTable : DataTable
    {
        public override void EndInit()
        {
            base.EndInit();
            this.TableNewRow += delegate(object sender, DataTableNewRowEventArgs e) { };
        }
    
        protected override void OnTableNewRow(DataTableNewRowEventArgs e)
        {
            base.OnTableNewRow(e);
            // your code here
        }
    }
    

提交回复
热议问题