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

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

c# 如何返回一個(gè)在工廠方法中指定泛型類的類

c# 如何返回一個(gè)在工廠方法中指定泛型類的類

PHP
犯罪嫌疑人X 2024-01-20 21:39:47
我想知道是否可以執(zhí)行這樣的方法,而不會(huì)在返回時(shí)進(jìn)行丑陋的轉(zhuǎn)換?    public static AbstractFileReader<T> GetReader<T>(string filename, T data)    {        if(data is string)        {            return GetTextFileReader(filename) as AbstractFileReader<T>;        }        else if(data is byte[])        {            return GetBytesFileReader(filename) as AbstractFileReader<T>;        }        else        {            Debug.LogError("There is no reader for that type of data : " + data.GetType().ToString());            return null;        }    }為了簡(jiǎn)單起見,這是我的架構(gòu):> AbstractFileReader<T> => The generic base class> AbstractTextFileReader : AbstractFileReader<string> => an abstract class> StandaloneTextFileReader : AbstractTextFileReader => the final implementation我的第一個(gè)想法是采用這樣的方法:    public static AbstractFileReader<T> GetReader<T>(string filename, T data)    {        if(data is string)        {            return StandaloneTextFileReader(filename);        }        else if(data is byte[])        {            return StandaloneBytesFileReader(filename);        }        else        {            Debug.LogError("There is no reader for that type of data : " + data.GetType().ToString());            return null;        }    }但我的編譯器似乎不接受它。有什么辦法可以實(shí)現(xiàn)這一點(diǎn)嗎?謝謝
查看完整描述

1 回答

?
元芳怎么了

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超7個(gè)贊

泛型在這里對(duì)你沒有任何幫助。

T您目前所使用的只是指定其中一個(gè)參數(shù)的類型(除了查詢其類型之外,您甚至不使用該參數(shù))。您可以像這樣輕松地編寫它AbstractFileReader GetReader(string filename, Object data)

泛型的全部要點(diǎn)是不關(guān)心Type 是什么(盡管您可以對(duì)其進(jìn)行限制),并且無(wú)論 TypeT是什么(例如Lists),泛型類公開的所有方法都以相同的方式運(yùn)行。

這里的情況并非如此。

因此,您根本不應(yīng)該在這里使用泛型。只需在某處有一個(gè)GetReaderForStringandGetReaderForBytes方法,并根據(jù)需要返回 aStandaloneTextFileReaderStandaloneBytesFileReader(或者完全放棄這些方法,只返回new適當(dāng)?shù)念悾?/p>


查看完整回答
反對(duì) 回復(fù) 2024-01-20
  • 1 回答
  • 0 關(guān)注
  • 193 瀏覽

添加回答

舉報(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)