我面临着一个场景,我需要创建N个对象的实例(实现一个接口)并从中调用一个方法,该方法的参数在实现该接口的每个类中可以有所不同,就像这样:
//Definition
class BaseOutput
{
public string Result {get; set;}
}
class BaseParam
{
public string Name {get; set;}
}
class CarParam : BaseParam
{
public string Wheels {get; set;}
}
class AirPlaneParam : BaseParam
{
public string Engines {get; set;}
}
interface Vehicle
{
IEnumerable<BaseOutput> Run(IEnumerable<BaseParam> parameters,
object anotherVal);
}
//Implementation
class Car : Vehicle
{
//Here the parameters type must be restricted to be only of type IEnumerable<CarParam>
public IEnumerable<BaseOutput> Run(IEnumerable<BaseParam> parameters, object anotherVal)
{
//Do something specific to the Car
}
}
class AirPlane : Vehicle
{
//Here the parameters type must be restricted to be only of type IEnumerable<AirPlaneParam>
public IEnumerable<BaseOutput> Run(IEnumerable<BaseParam> parameters, object anotherVal)
{
//Do something specific to the AirPlane
}
}
需要该限制来防止在每个类的特定属性的具体使用上出现任何问题。
肥皂起泡泡
相关分类