开发者

Method overriding in C#

开发者 https://www.devze.com 2023-03-13 02:00 出处:网络
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 behav

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.


Your using the new keyword in your derived class on your OnPrev/OnNext methods - what you want to do is "override" the base class methods eg use the override keyword.


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");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消