How to restrict inheritance types from a hierarchy level?

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

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

Edit

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

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

public abstract class Motor
{
    public virtual ICollection<Veiculo> Veiculos { get; set; }
}
    
asked by anonymous 24.06.2014 / 19:30

1 answer

7

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

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> { }
    
24.06.2014 / 19:50