简体   繁体   中英

What is the correct way to make an inherited event-handler fire before its base’s event-handler?

I have a base class (itself inheriting from Panel) and an inherited class. The base class has a Click event-handler.

What is the correct way to make a Click event-handler in the inherited class fire before the base's handler, and only then execute the base's?

My workaround is of the following form:

class first : Panel
{
    public first()
    {
        Click += first_Click;
    }

    protected virtual void first_Click(object sender, EventArgs e)
    {
        doHandler();
    }

    protected void doHandler()
    {
        MessageBox.Show("first");
    }
}

class derived : first
{
    protected override void first_Click(object sender, EventArgs e)
    {
        MessageBox.Show("derived");
        doHandler();
    }
}

Is there a straightforward way?

Thanks.

There's no point in listening for your own events. Override the OnClick() method instead.

class derived : first
{
    protected override void OnClick(EventArgs e)
    {
        MessageBox.Show("derived");
        base.OnClick(e);
    }
}

Or call base.OnClick() first to alter the order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM