2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使參數(shù)類型為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
}
}
這將限制您可以傳遞的內(nèi)容:
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
您會(huì)發(fā)現(xiàn)困難的地方是,您是否需要在不知道其通用類型的情況下代表一堆車輛:
var vehicles = new List<Vehicle<BaseParam>>();
vehicles.Add(new Car()); // compile-time exception.
- 2 回答
- 0 關(guān)注
- 152 瀏覽
添加回答
舉報(bào)