![](/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.