c# - 派生属性?

标签 c# polymorphism

是否有声明派生属性的方法?

public class Vehicle {

    public VehicleType Type { get; set; }

}

public class Car : Vehicle {

    public CarType Type { get; set; }

}

public class VehicleType {}

public class CarType : VehicleType {}

这样当我调用 Car.Type;我只看到车型?

最佳答案

你不能那样做。 Type 属性必须在基类和派生类中具有相同的类型。

一种方法是使用泛型:

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();

关于c# - 派生属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132117/

相关文章:

c# - Visual Studio 2010 中的代码便签本扩展 - 如何?

c# - 是否可以仅使用用户名和密码从我的 .net core 应用程序登录 Azure?

java - 使用 Jackson 进行多态反序列化,而 'type' 和 'value' 是单独的字段

c++ - 使用堆栈分配的对象将异构对象存储在 vector 中

c# - System.IO.Directory.Exists 在 LINQ 语句中失败,但在 foreach 循环中不失败

c# - 如何使用 LINQ 从表中给定值找到范围之间的最高数字

java - 使用多态参数覆盖方法

c++ - vector 迭代器 -> 打印类(缺少参数)

c# - 如何在 C# 中对开放类型进行泛型多态?

c# - WPF:在代码隐藏中获取控件绑定(bind)到的属性