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 關注
- 150 瀏覽
添加回答
舉報