亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

每個類實現的接口方法的強制參數為具體類型

每個類實現的接口方法的強制參數為具體類型

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 關注
  • 150 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號