为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
素胚勾勒不出你 2021-05-06 10:13:40
我面临着一个场景,我需要创建N个对象的实例(实现一个接口)并从中调用一个方法,该方法的参数在实现该接口的每个类中可以有所不同,就像这样://Definitionclass 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);}//Implementationclass 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    }}需要该限制来防止在每个类的特定属性的具体使用上出现任何问题。
查看完整描述

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.


查看完整回答
反对 回复 2021-05-29
  • 2 回答
  • 0 关注
  • 115 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信