我知道标题可能没有意义,但下面应该解释我的困境。
所以我正在为我的 MonoGame 游戏制作一个用户界面。我有一个抽象类 Clickable
,它包含一些在某些操作发生时调用的基本方法(为了清楚起见,我省略了其他一些事情):
abstract public class Clickable
{
public abstract void OnClick(Vector2 pos, MouseButton button);
public abstract void OnHover(Vector2 pos);
public abstract void OnUnHover(Vector2 pos);
public abstract void OnHold(Vector2 pos, MouseButton button);
public abstract void OnRelease(Vector2 pos, MouseButton button);
}
这些方法中的每一个都可以由我的 ControlManager
调用,它会循环遍历 Clickable
的列表以查看上述方法中的任何一个当前是否适用。
然后我有一个继承自 Clickable
的类,名为 Control
(再次精简):
abstract public class Control : Clickable
{
public abstract void DrawBackground(SpriteBatch sb, GameTime gt);
public abstract void DrawMiddleground(SpriteBatch sb, GameTime gt);
public abstract void DrawForeground(SpriteBatch sb, GameTime gt);
}
因此,我的用户控件继承自此。我的问题是,为了拥有一个可编译的类,我必须覆盖所有这些抽象方法。
取未完成的TextBox
类:
class TextBox : Control
{
Typeable typeable;
public TextBox(Vector2 position, int width, int height, string text, SpriteFont font, Control alignedTo, Dictionary<String, Texture2D> images) :
base(position, width, height, alignedTo, images)
{
typeable = new Typeable(text, font, position);
}
public override void OnClick(Vector2 position, MouseButton button)
{
//Cursor functions will go here
}
public override void OnHold(Vector2 pos, MouseButton button)
{
}
public override void OnHover(Vector2 pos)
{
}
public override void OnRelease(Vector2 pos, MouseButton button)
{
}
public override void OnUnHover(Vector2 pos)
{
}
public override void DrawBackground(SpriteBatch sb, GameTime gt)
{
}
public override void DrawMiddleground(SpriteBatch sb, GameTime gt)
{
//draw textbox background
}
public override void DrawForeground(SpriteBatch sb, GameTime gt)
{
//draw textbox text
}
}
如您所见,(注释所在的位置),我只会使用一些我被迫声明的方法。
有没有一种方法可以让我的抽象类中有基方法而不是有覆盖,(只是有选择权)?请记住,像 TextBox
这样的类不会实现 OnHold
方法,如果用户按住鼠标,它仍然会被 ControlManager
调用按下控件上的按钮。
最佳答案
最后,您的问题的答案是否。对于要实例化(可实例化?)的类,它必须重写每个抽象方法(或继承自实现了它未实现的方法的类)。
要使这个“可选”,只需将它们标记为 virtual
而不是 abstract
,并在基类中提供默认(空)实现。仅当您确实希望所有派生类都实现该方法时才使用 abstract
。
标记为 virtual
的方法必须有一个实现,即使它是空的:
public virtual void MyFunc()
{
}
有效。这将被调用,除非派生对象具有:
public override void MyFunc()
{
//Some implementation
}
基本上,在 C# 中某处不能有没有方法体的方法声明。
关于c# - 有没有一种方法允许子类只覆盖 -some- 父类抽象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24046215/