简体   繁体   中英

why does overriding method executes twice instead of once in c#?

I have a base class and a derived class . The base class has a simple button with a virtual protected button click method.

I am using the ovverride keyword (not using new as i want the buttonclick method in the derived class to override the base class buttonclick method)

However , the code inside the derived class buttonclick method executes twice instead of once

Here is the code example

In the Base Class:

this.ok.Click += new System.EventHandler(this.ok_Click);
    protected virtual void ok_Click(object sender, EventArgs e)
            {
                MessageBox.Show("From the Base class");
            }

In the Derived Class:

 this.ok.Click += new System.EventHandler(this.ok_Click);
 protected override void ok_Click(object sender, EventArgs e)
            {
                MessageBox.Show("From the Derived class");
            }

You haven't said what's actually calling the buttonclick method, but I suspect it's an event handler... and I suspect you're subscribing to it in both the subclass and base class constructors. Don't do that - you only need to subscribe once.

(If that's not the case, please show a short but complete example.)

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