none
Interface Implementation RRS feed

  • Pregunta

  • Hi, today I was thinking something about Interfaces implementation, and I got the idea to do something like this:

    so, I thought write a Motor class, and I thought this was the best option:

    public class Motor : IRotational , IActuator
    {...}

    then I tried to do something like this:

    IElectromechanic e = new Motor();

    and obviusly it doesn't work. I know why this doesn't work, because the interface IElectromechanic could have more members and the Implementation of IElectromechanic would be bigger than implement IElectric and IMechanic.

    And the question here is:

    Is there a way to do something like this? :

    Say that IElectromechanic is equal to IMechanic and IElectric and it doesn't extend from them, because in that way I can be shure that I can get the IElectric and IMechanic members from the motor, because actually, IActuator extends from IElectric and IRotational extends from IMechanic.

    Or the only way to do that is get the Interface members with both Interfaces separated:

    Motor motor = new Motor();
    
    IElectric e = motor;
    IMechanic m = motor;
    
    



    jueves, 30 de mayo de 2019 5:14

Respuestas

  • No, you can't make IElectromechanic "equal" to IMechanic and IElectric. You could put IElectromechanic "above" both of them and have IMechanicar and IElectric extend it, but this is probably not what you want, although it would work for assigning to it an instance of Motor.

    In practice, what everybody does is precisely what you did in your last example: create an instance of Motor and assign it to both IElectric and IMechanic.

    jueves, 30 de mayo de 2019 5:57
    Moderador

Todas las respuestas

  • No, you can't make IElectromechanic "equal" to IMechanic and IElectric. You could put IElectromechanic "above" both of them and have IMechanicar and IElectric extend it, but this is probably not what you want, although it would work for assigning to it an instance of Motor.

    In practice, what everybody does is precisely what you did in your last example: create an instance of Motor and assign it to both IElectric and IMechanic.

    jueves, 30 de mayo de 2019 5:57
    Moderador
  • Thank you! i think I'm goint to make it like that, but, It would be a nice concept to add right?, it could be posible in a new C# version with a new modifier.

    public MODIFIER interface IElectromechanic : IMechanic , IElectric;

    but what ever hahahaha, thank you for your answer.
    jueves, 30 de mayo de 2019 19:34