C# 中的方法重写
这是一个相当简单的问题,我有一个实现常见 GUI 元素的基类,以及一系列我想重写给定方法的子类,以便它们可以在公共控件上实现自己的行为(即 Prev 和 Next)按钮)。
所以我有这个
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(){}
}
,这是子类之一
public class MissionSelectGUI : MetalGUI {
new void OnGUI()
{
base.OnGUI();
}
new protected void OnPrev()
{
Application.LoadLevel("mainMenu");
}
new protected void OnNext()
{
Application.LoadLevel("selectPlayer");
}
}
(这两个类都被剥离了对于这种情况来说不必要的东西)
问题是,当我实例化 MissionSelectGUI
的成员时,<正在调用 MetalGUI
上的 code>OnPrev 和 OnNext
,而不是重写方法。这是为什么呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
new
遮蔽(或隐藏)该方法(它创建一个具有相同名称的 new 方法)。要覆盖它(从而在类的虚函数表中添加一个条目),请使用override
。例如: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), useoverride
. For instance:我认为您应该使用 overrides 关键字而不是新关键字。请参阅 http://msdn.microsoft.com /en-us/library/51y09td4(v=vs.71).aspx#vclrfnew_newmodifier。
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 关键字。
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.
您没有重写这些方法,只是使用
new
隐藏它们。这是您覆盖它们的方式(并允许其他类覆盖此实现):
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):