猿问

每个类实现的接口方法的强制参数为具体类型

我面临着一个场景,我需要创建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

    }

}

需要该限制来防止在每个类的特定属性的具体使用上出现任何问题。


素胚勾勒不出你
浏览 127回答 2
2回答

肥皂起泡泡

您可以使参数类型为generic。interface Vehicle<in TParam> where TParam : BaseParam{&nbsp; &nbsp; IEnumerable<BaseOutput> Run(IEnumerable<TParam> parameters,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; object anotherVal);}//Implementationclass Car : Vehicle<CarParam>{&nbsp; &nbsp; public IEnumerable<BaseOutput> Run(IEnumerable<CarParam> parameters, object anotherVal)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Do something specific to the Car&nbsp; &nbsp; }}class AirPlane : Vehicle<AirPlaneParam>{&nbsp; &nbsp; public IEnumerable<BaseOutput> Run(IEnumerable<AirPlaneParam> parameters, object anotherVal)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Do something specific to the AirPlane&nbsp; &nbsp; }}这将限制您可以传递的内容:new Car().Run(new CarParam[0], new object()); // allowednew Car().Run(new BaseParam[0], new object()); // compile-time errornew Car().Run(new AirPlaneParam[0], new object()); // compile-time error您会发现困难的地方是,您是否需要在不知道其通用类型的情况下代表一堆车辆:var vehicles = new List<Vehicle<BaseParam>>();vehicles.Add(new Car()); // compile-time exception.
随时随地看视频慕课网APP
我要回答