Question

Is there a way of declaring derived properties?

public class Vehicle {

    public VehicleType Type { get; set; }

}

public class Car : Vehicle {

    public CarType Type { get; set; }

}

public class VehicleType {}

public class CarType : VehicleType {}

so that when I call Car.Type; I only see car types?

Était-ce utile?

La solution

You can't do that. The Type property has to have the same type in both the base and the derived classes.

One way of doing this is using generics:

public class Vehicle<TVehicleType> where TVehicleType: VehicleType {

    public TVehicleType Type { get; set; }
}

public class Car : Vehicle<CarType> {  }


Car car = new Car();
car.Type = new CarType();

Autres conseils

Properties can indeed be declared abstract or virtual on a base class and overridden by a derived class. But when using inheritance, you cannot change the input parameters or return type of the function/property.

If you find that you want a totally different type for the same property between the derived and the base, you may have a design smell. Perhaps inheritance isn't what you actually want.

If you still think you need something like this, you might be able to leverage generics:

class Base<T>
{
    public virtual T MyProp { /* ... */ }
}

// Derived class that uses string for prop
class Derived1 : Base<string>
{
    public override string MyProp { /* ... */ }
}

// Derived class that uses int for prop
class Derived2 : Base<int>
{
    public override int MyProp { /* ... */ }
}

Something like this should work:

public class Car : Vehicle {

    public CarType Type
    {
        get { return base.Type; }
        set { base.Type = value; }
    }
}

I would suggest not using the name "Type" because it's a reserved member already.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top