简体   繁体   中英

Force derived class to implement interface

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 (fe KeyCode).
It just knows the type of the Buttons, which is T.

  1. Solution

Adding the following interface to InputDevice(T)

public interface IInputDevice{
    void GetButton(System.Type);
}
  • Problem:

InputDevice(T ) has to implement it, which it can not.
I do not know the return type T of InputDevice(T)

  1. Solution:

Adding the method manually in all derivers.

  • Problem:

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...
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM