作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有 ElectricCar
和 DieselCar
类,它们继承自 Vehicle
。它们分别有 ElectricEngine
和 DieselEngine
。
两个引擎类都有 Start
方法。最初我在两个汽车子类中都实现了 StartAllEngines()
,但我发现它重复性很高,所以我想在 vehicle
基类中将其抽象。
问题是,如何在基类中定义engines
的类型? dynamic
是一个选项,但我感觉不太好安全使用它。
或者我不应该抽象这个方法?但是这样就违反了DRY原则。
public class Vehicle{
protected List<???Engine> engines; // What should be the type?
public void StartAllEngines (){
foreach (???Engine engine in this.engines){
engine.Start();
}
}
}
public class ElectricCar: Vehicle{
public ElectricCar(){
this.engines = List<ElectricEngine>();
}
}
public class DieselCar: Vehicle{
public DieselCar(){
this.engines = List<DieselEngine>();
}
}
public class ElectricEngine: Engine {...}
public class DieselEngine: Engine {...}
最佳答案
在带有 Engine
的基类中使用泛型参数作为约束:
public class Vehicle<TEngine> where TEngine: Engine
{
protected List<TEngine> engines = new List<TEngine>();
public void StartAllEngines (){
foreach (TEngine engine in this.engines){
engine.Start();
}
}
}
public class ElectricCar: Vehicle<ElectricEngine>
{
public ElectricCar(){
}
}
public class DieselCar: Vehicle<DieselEngine>
{
public DieselCar(){
}
}
public class ElectricEngine: Engine {...}
public class DieselEngine: Engine {...}
关于c# - 抽象子类共有的方法,但它使用子类特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793690/
我有一个包含 28 列的数据库。第一列是代码,第二列是名称,其余是值。 public void displayData() { con.Open(); MySqlDataAdapter
Redmi 官方今天宣布了 Redmi智能电视 A 系列新品,称即将开放预约。 官方并未公布 Redmi智能电视 A 系列新品的具体信息,但给出的海报显示该系列提供五种尺寸:32 英寸、43
我是一名优秀的程序员,十分优秀!