Reputation: 4572
I am here today (like yesterday) with another weird interface question.
I have a 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
}
}
As you can see, this class cannot be instantiated.
A class that derives from it might be able to be instantiated.
This is a subclass:
public sealed class Keyboard : InputDevice<KeyboardButton> {
public Keyboard() {
buttons.Add(new KeyboardButton(KeyCode.A));
}
}
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
}
For the Mouse : InputDevice<MouseButton>
it would look like:
public MouseButton GetButton(MouseButtons Button) {
//Retrieve button
}
Note: MouseButton (class) != MouseButtons (enum)
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.
Adding the following interface to InputDevice(T)
public interface IInputDevice{
void GetButton(System.Type);
}
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.
Upvotes: 5
Views: 3662
Reputation: 7301
Just declare InputDevice<T>
abstract
public abstract class InputDevice<T>
{
protected abstract void GetButton(System.Type type);
}
furthermore you can set InputDevice<T>
as an inheritor of IInputDevice
this will work too.
Upvotes: 1
Reputation: 57202
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...
}
}
Upvotes: 7