强制派生类实现接口

Noe*_*mer 5 c# generics inheritance enums 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
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此类无法实例化.
从中派生的类可能能够实例化.

这是一个子类:

public sealed class Keyboard : InputDevice<KeyboardButton> {

    public Keyboard() {
        buttons.Add(new KeyboardButton(KeyCode.A));
    }
}
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.
现在我想要InputDevice<T>提供一种GetButton()方法的所有派生.
该方法应该将设备的按钮的枚举类型作为参数.

对于Keyboard课程,它看起来像这样:

public KeyBoardButton GetButton(KeyCode Code) {
    //Retrieve button
}
Run Code Online (Sandbox Code Playgroud)

对于Mouse : InputDevice<MouseButton>它看起来像:

public MouseButton GetButton(MouseButtons Button) {
    //Retrieve button
}
Run Code Online (Sandbox Code Playgroud)

注意: MouseButton (class) != MouseButtons (enum)

每个派生者都InputDevice(T)必须实现该方法.
但我不希望InputDevice(T)自己实现它,因为它不知道按钮的枚举类型(fe KeyCode).
它只知道按钮的类型,即T.

添加以下接口 InputDevice(T)

public interface IInputDevice{
    void GetButton(System.Type);
}
Run Code Online (Sandbox Code Playgroud)
  • 问题:

InputDevice(T)必须实现它,它不能.
我不知道返回类型TInputDevice(T)

  1. 解:

在所有派生程序中手动添加方法.

  • 问题:

派生不保证提供方法.


你有解决方案吗?我试图解决这个问题时感到非常困惑.

Pao*_*sco 7

您可以使基类抽象并更改其定义以包含键代码类型:

public abstract class InputDevice<TButton, TEnum> where TButton : Button {
    public abstract TButton GetButton(TEnum Code);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样定义派生类:

public sealed class Keyboard : InputDevice<KeyboardButton, KeyCode> {
    public override KeyboardButton GetButton(KeyCode Code) {
        // implementation here...
    }
}
Run Code Online (Sandbox Code Playgroud)