2 回答
TA贡献1829条经验 获得超6个赞
您可以使参数类型为generic。
interface Vehicle<in TParam> where TParam : BaseParam
{
IEnumerable<BaseOutput> Run(IEnumerable<TParam> parameters,
object anotherVal);
}
//Implementation
class Car : Vehicle<CarParam>
{
public IEnumerable<BaseOutput> Run(IEnumerable<CarParam> parameters, object anotherVal)
{
//Do something specific to the Car
}
}
class AirPlane : Vehicle<AirPlaneParam>
{
public IEnumerable<BaseOutput> Run(IEnumerable<AirPlaneParam> parameters, object anotherVal)
{
//Do something specific to the AirPlane
}
}
这将限制您可以传递的内容:
new Car().Run(new CarParam[0], new object()); // allowed
new Car().Run(new BaseParam[0], new object()); // compile-time error
new Car().Run(new AirPlaneParam[0], new object()); // compile-time error
您会发现困难的地方是,您是否需要在不知道其通用类型的情况下代表一堆车辆:
var vehicles = new List<Vehicle<BaseParam>>();
vehicles.Add(new Car()); // compile-time exception.
- 2 回答
- 0 关注
- 126 浏览
添加回答
举报