![](/img/trans.png)
[英]Is there a way to force a derived class to implement an abstract class or an interface nested in base class?
[英]Force derived class to implement interface
我今天在这里(就像昨天一样)有另一个奇怪的界面问题。
我有一节课:
public class InputDevice<T> where T : Button {
protected List<T> buttons = new List<T>();
protected InputDevice() {
//Only allow instanciation from within a derived class
}
}
如您所见,此类无法实例化。
从中派生的类可能能够实例化。
这是一个子类:
public sealed class Keyboard : InputDevice<KeyboardButton> {
public Keyboard() {
buttons.Add(new KeyboardButton(KeyCode.A));
}
}
到现在为止还挺好。
现在,我希望InputDevice<T>
所有派生程序都提供GetButton()
方法。
该方法应该将设备的按钮的枚举类型作为参数。
对于Keyboard
类,它看起来像这样:
public KeyBoardButton GetButton(KeyCode Code) {
//Retrieve button
}
对于Mouse : InputDevice<MouseButton>
它看起来像:
public MouseButton GetButton(MouseButtons Button) {
//Retrieve button
}
注意: MouseButton (class) != MouseButtons (enum)
InputDevice(T)
每个派生必须实现该方法。
但我不希望InputDevice(T)
本身实现它,因为它不知道按钮的枚举类型(fe KeyCode)。
它只知道按钮的类型,即T.
将以下接口添加到InputDevice(T)
public interface IInputDevice{
void GetButton(System.Type);
}
InputDevice(T
)必须实现它,它不能。
我不知道InputDevice(T)
的返回类型T
在所有派生程序中手动添加方法。
派生不保证提供方法。
你有解决方案吗? 我试图解决这个问题时感到非常困惑。
您可以使基类抽象并更改其定义以包含键代码类型:
public abstract class InputDevice<TButton, TEnum> where TButton : Button {
public abstract TButton GetButton(TEnum Code);
}
然后你可以像这样定义派生类:
public sealed class Keyboard : InputDevice<KeyboardButton, KeyCode> {
public override KeyboardButton GetButton(KeyCode Code) {
// implementation here...
}
}
只需声明InputDevice<T>
abstract
public abstract class InputDevice<T>
{
protected abstract void GetButton(System.Type type);
}
此外,您可以将InputDevice<T>
设置为IInputDevice
的继承者,这也将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.