C# 强制派生类实现接口
我今天(和昨天一样)在这里提出另一个奇怪的接口问题 我有一门课:C# 强制派生类实现接口,c#,generics,inheritance,interface,enums,C#,Generics,Inheritance,Interface,Enums,我今天(和昨天一样)在这里提出另一个奇怪的接口问题 我有一门课: 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 class InputDevice<T> where T : Button {
protected List<T> buttons = new List<T>();
protected InputDevice() {
//Only allow instanciation from within a derived class
}
}
对于鼠标:InputDevice
它看起来像:
public KeyBoardButton GetButton(KeyCode Code) {
//Retrieve button
}
public MouseButton GetButton(MouseButtons Button) {
//Retrieve button
}
注意:MouseButton(类)!=鼠标按钮(枚举)
InputDevice(T)
的每个派生程序都必须实现该方法。但是我不希望
InputDevice(t)
本身实现它,因为它不知道按钮的枚举类型(f.e.KeyCode)它只知道按钮的类型,即T。
InputDevice(T)
- 问题:
输入设备(T
)必须实现它,但它不能实现。我不知道
InputDevice(T)
- 问题:
你有解决这个问题的办法吗?当我试图解决这个问题时,我感到非常困惑。只需声明
InputDevice
摘要
public abstract class InputDevice<T>
{
protected abstract void GetButton(System.Type type);
}
公共抽象类InputDevice
{
受保护的抽象无效按钮(System.Type);
}
此外,您可以将
InputDevice
设置为IInputDevice
的继承者,这也会起作用。您可以将基类抽象并更改其定义,以包括键代码类型:
public abstract class InputDevice<TButton, TEnum> where TButton : Button {
public abstract TButton GetButton(TEnum Code);
}
公共抽象类InputDevice,其中TButton:按钮{
公共摘要TButton GetButton(TEnum代码);
}
然后您可以像这样定义派生类:
public sealed class Keyboard : InputDevice<KeyboardButton, KeyCode> {
public override KeyboardButton GetButton(KeyCode Code) {
// implementation here...
}
}
公共密封类键盘:输入设备{
公共覆盖键盘按钮GetButton(按键代码){
//在这里实现。。。
}
}
如果不想直接实例化类,为什么不使用抽象类?这将是执行此操作的标准方法。您可以说GetButton
,但返回类型无效:\n当涉及到派生程序时,不保证提供方法。。答案是:是的,他们不需要在方法中做任何事情。你是说在接口中可能重复@SriramSakthivel?是的,正如前面所说的,接口不知道返回类型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...
}
}