第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

每個(gè)類實(shí)現(xiàn)的接口方法的強(qiáng)制參數(shù)為具體類型

每個(gè)類實(shí)現(xiàn)的接口方法的強(qiáng)制參數(shù)為具體類型

C#
素胚勾勒不出你 2021-05-06 10:13:40
我面臨著一個(gè)場(chǎng)景,我需要?jiǎng)?chuàng)建N個(gè)對(duì)象的實(shí)例(實(shí)現(xiàn)一個(gè)接口)并從中調(diào)用一個(gè)方法,該方法的參數(shù)在實(shí)現(xiàn)該接口的每個(gè)類中可以有所不同,就像這樣://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    }}需要該限制來防止在每個(gè)類的特定屬性的具體使用上出現(xiàn)任何問題。
查看完整描述

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.


查看完整回答
反對(duì) 回復(fù) 2021-05-29
  • 2 回答
  • 0 關(guān)注
  • 152 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)