强制派生类实现接口 [英] Force derived class to implement interface
问题描述
我今天在这里(就像昨天一样)在这里,还有另一个奇怪的界面问题。
I am here today (like yesterday) with another weird interface question.
我有一堂课:
public class InputDevice<T> where T : Button {
protected List<T> buttons = new List<T>();
protected InputDevice() {
//Only allow instanciation from within a derived class
}
}
如您所见,此类无法实例化。
从其派生的类可以被实例化。
As you can see, this class cannot be instantiated.
A class that derives from it might be able to be instantiated.
这是一个子类:
public sealed class Keyboard : InputDevice<KeyboardButton> {
public Keyboard() {
buttons.Add(new KeyboardButton(KeyCode.A));
}
}
到目前为止一切都很好。
现在,我希望所有 InputDevice< T>
的派生器提供一个 GetButton()
方法。
该方法应将设备按钮的枚举类型作为参数。
用于键盘
这样的类:
So far so good.
Now I'd like all derivers of InputDevice<T>
to provide a GetButton()
method.
That method should take in the enum-Type of the Device's buttons as an argument.
For the Keyboard
class it would look like this:
public KeyBoardButton GetButton(KeyCode Code) {
//Retrieve button
}
对于 Mouse:InputDevice< MouseButton>
如下所示:
For the Mouse : InputDevice<MouseButton>
it would look like:
public MouseButton GetButton(MouseButtons Button) {
//Retrieve button
}
注意: MouseButton(class)!= MouseButtons(enum)
每个 InputDevice( T)
必须实现该方法。
但是我不希望 InputDevice(T)
自己实现它,因为使用它不知道Button的枚举类型(例如关键代码)。
它只知道按钮的类型,即T。
Each deriver of InputDevice(T)
must implement that method.
But I don't want the InputDevice(T)
itself to implement it because it doesn't know the enum-type of the Buttons (f.e. KeyCode).
It just knows the type of the Buttons, which is T.
- 解决方案
- Solution
将以下接口添加到 InputDevice(T)
public interface IInputDevice{
void GetButton(System.Type);
}
- 问题:
- Problem:
- 解决方案:
- Solution:
- 问题:
- Problem:
InputDevice(T
)必须实现它,但不能实现。
我不知道 InputDevice(T)
<的返回类型 T
br>
InputDevice(T
) has to implement it, which it can not.
I do not know the return type T
of InputDevice(T)
在所有派生器中手动添加方法。
Adding the method manually in all derivers.
不能保证提供方法。
Derivers are not guaranteed to provide the methods.
您有解决方案吗?为了这?
Do you have a solution for this? I got really confused while trying to sort this out.
推荐答案
您可以使基类抽象化并更改其定义以包括以下内容:关键代码类型:
You could make the base class abstract and change its definition to include the key code type:
public abstract class InputDevice<TButton, TEnum> where TButton : Button {
public abstract TButton GetButton(TEnum Code);
}
然后您可以定义派生类,如下所示:
Then you could define the derived classes like this:
public sealed class Keyboard : InputDevice<KeyboardButton, KeyCode> {
public override KeyboardButton GetButton(KeyCode Code) {
// implementation here...
}
}
这篇关于强制派生类实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!