How to restrict inherited types from a hierarchy level?

Asked

Viewed 139 times

4

Given the hypothetical model below:

public abstract class Veiculo
{
    public Motor Motor { get; set; }
}

public class Aviao : Veiculo { }

public abstract class Motor { }

public class MotorCarro : Motor { }

public class MotorAviao : Motor { }

It is possible to restrict the type of Motor for the class Aviao as just MotorAviao and its derivatives? Or, what would be the best solution for this scenario?

Edit

The same scenario, but with an attribute that is quite common for cases of aggregation: a list of all aggregated objects on the other side of the relationship.

The class Motor should know all vehicles that use it. Would look like this:

public abstract class Motor
{
    public virtual ICollection<Veiculo> Veiculos { get; set; }
}
  • 1

    This is quite different from the original question - I think the correct one would open a second question.

1 answer

7


The most common way to solve this type of problems is to 'make the Generic base class, and let the derived class choose its engine type.

public abstract class Veiculo<TMotor> where TMotor : Motor
{
    public TMotor Motor { get; set; }
}

//aviao = veiculo com motor de aviao
public class Aviao : Veiculo<MotorAviao> { }

public class Carro : Veiculo<MotorCarro> { }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.