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

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

在 Func 中使用泛型類(lèi)型參數(shù),并使用特定類(lèi)型調(diào)用 Func?

在 Func 中使用泛型類(lèi)型參數(shù),并使用特定類(lèi)型調(diào)用 Func?

C#
素胚勾勒不出你 2021-10-09 19:47:05
我有以下方法在 aT中使用Func:public void DoSomething<T>(string someString, Func<T, bool> someMethod) {        if(someCondition)     {        string A;        bool resultA = someMethod(A);    }    else     {        string[] B;        bool resultB = someMethod(B);    }        // Some other stuff here ...}我正在DoSomething以下列方式調(diào)用該方法:DoSomething<string>("abc", someMethod);DoSomething<string[]>("abc", someMethod);并且 someMethod 存在,具有以下定義:bool someMethod(string simpleString);bool someMethod(string[] stringArray);現(xiàn)在編譯失敗,方法中出現(xiàn)以下錯(cuò)誤DoSomething:cannot convert from 'string' to 'T'cannot convert from 'string[]' to 'T'我無(wú)法弄清楚問(wèn)題是否有解決方案,或者我嘗試的方法不可行。它看起來(lái)類(lèi)似于問(wèn)題如何使用泛型類(lèi)型參數(shù)傳入 func?,雖然它對(duì)我的場(chǎng)景沒(méi)有幫助。
查看完整描述

2 回答

?
滄海一幻覺(jué)

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

你的例子看起來(lái)有點(diǎn)不一致,但如果你寫(xiě)的是一般的東西,它應(yīng)該看起來(lái)更像這樣:


public void DoSomething<T>(string someString, Func<T, bool> someMethod) 

{

    T a;

    someMethod(a);

}

請(qǐng)注意,不是使用if在類(lèi)型之間進(jìn)行選擇,然后將類(lèi)型聲明為 astring或string[],而是簡(jiǎn)單地將類(lèi)型聲明為T(mén),它會(huì)在編譯代碼時(shí)被替換,以便它適用于函數(shù)。


當(dāng)您發(fā)現(xiàn)自己使用ifor在類(lèi)型之間進(jìn)行選擇時(shí)switch case,您可能不需要通用解決方案;事實(shí)上,這個(gè)邏輯根本不是通用的。它是具體的。在這種情況下,只需編寫(xiě)兩個(gè)原型:


public void DoSomething(string someString, Func<string, bool> someMethod) 

{    

    string A;

    bool resultA = someMethod(A);

}



public void DoSomething(string someString, Func<string[], bool> someMethod) 

{    

    string[] A;

    bool resultA = someMethod(A);

}

這稱(chēng)為方法重載。編譯器將通過(guò)從提供的函數(shù)推斷類(lèi)型來(lái)自動(dòng)選擇具有正確參數(shù)的正確方法。


查看完整回答
反對(duì) 回復(fù) 2021-10-09
?
繁花不似錦

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

您可以通過(guò)反射實(shí)現(xiàn)它:


public void DoSomething<T>(string someString, Func<T, bool> someMethod)

{

    var args = new Dictionary<Type, object>

    {

        [typeof(string)] = "string", //string A;

        [typeof(string[])] = new[] { "string" }, //string[] B;

    };

    var arg = args[typeof(T)];

    var result = (bool)someMethod.Method.Invoke(someMethod.Target, new[] { arg });

}

用法:


DoSomething<string>("abc", someMethod);

DoSomething<string[]>("abc", someMethod);


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

添加回答

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