简体   繁体   中英

Method overriding in C#

This is a rather simple question, I have a base class which implements common GUI elements, and a series of child classes which I want to override a given method, so they can implement their own behavior on a common control (namely, Prev and Next buttons).

So I have this

public class MetalGUI : BaseGUI {
    new protected void OnGUI()
    {
        base.OnGUI();
        if(GUI.Button(prevRect, "BACK", "ButtonLeft"))
            OnPrev();

        if(GUI.Button(nextRect, "NEXT", "ButtonRight"))
            OnNext();

    }

    virtual protected void OnPrev(){}
    virtual protected void OnNext(){}
}

and this is one of the child classes

public class MissionSelectGUI : MetalGUI {
    new void OnGUI()
    {
        base.OnGUI();
    }

    new protected void OnPrev()
    {
        Application.LoadLevel("mainMenu");
    }
    new protected void OnNext()
    {
        Application.LoadLevel("selectPlayer");
    }
}

(both classes have been stripped off the stuff non-essential for this case)

The thing is that when I have a member of MissionSelectGUI instantiated, the OnPrev and OnNext on MetalGUI is getting called instead of the overriden methods. Why is this?

Because new shadows (or hides) the method (it creates a new method with the same name). To override it (thus adding an entry in the class' vtable), use override . For instance:

override protected void OnPrev()
{
    Application.LoadLevel("mainMenu");
}

I think you should be using the overrides keyword not the new one. see http://msdn.microsoft.com/en-us/library/51y09td4(v=vs.71).aspx#vclrfnew_newmodifier .

您在OnPrev / OnNext方法的派生类中使用new关键字-您要做的是“覆盖”基类方法,例如,使用override关键字。

You have not overridden the methods, just hidden them using new .

This is how you would override them (and allow further classes to override this implementation):

override protected void OnPrev()
{
    Application.LoadLevel("mainMenu");
}

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