2016-10-05 31 views
1

我想發送一個params對象[i]給T函數,但我無法找到正確的語法。如何將params對象[i]傳遞給C#中的模板函數#

這裏顯示的是什麼,我試圖達到的上下文的示例:

private bool decodeValue<T>(int id,ref T item, string code) 
{ 

    if(!TypeDescriptor.GetConverter (item).CanConvertFrom(typeof(string))) 
    { 
     errorThrow (id + 2); 
     return false; 
    } 

    try 
    { 
     item = ((T)TypeDescriptor.GetConverter (item).ConvertFromString (code)); 
    } 
    catch 
    { 
     errorThrow (id + 2); 
     //item = default(T); 
     return false; 
    } 

    return true; 
} 

private bool decodeValues(string[] code, int id, params object[] items) 
{ 
    for (int i = 0; i < items.Length; i++) 
    { 
     System.Type t = items [i].GetType(); 
     //in this part i cant find the correct syntax 
     if(decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2])) 
     { 

     } 
    } 

    return false; 
} 

在生產線decodeValue<(t)items[i]>(id, ref items[i] as t, code[i+2] 不管我什麼語法,編譯器告訴我,>後,預計一)

我可以將函數decodeValue內聯到for循環中,但我認爲有一種更優雅的方式。有什麼建議麼?

+0

也不起作用 if(decodeValue (id,ref items [i],code [i + 2])) –

+0

爲什麼你首先需要'T'?你的代碼看起來像你可以只使用'ref object item' – Nico

+0

,因爲我首先製作了decodeValue,之後我對自己說,這樣做會更好,因此我添加了decodeValues並嘗試將其調整爲decodeValue。 decodeValue起初是一個很好的使用模板,因爲我發送的每個消息的硬編碼一個接一個。 –

回答

4

在你的例子中,你替換項目的內容。爲什麼甚至需要模板化功能?只是這樣做:

private bool decodeValue(int id,ref object item, string code) 
{ 

    if(!TypeDescriptor.GetConverter(item).CanConvertFrom(typeof(string))) 
    { 
     errorThrow (id + 2); 
     return false; 
    } 
    try 
    { 
     item = TypeDescriptor.GetConverter(item).ConvertFromString(code); 
    } 
    catch 
    { 
     errorThrow (id + 2); 
     return false; 
    } 

    return true; 
} 

private bool decodeValues(string[] code, int id, params object[] items) 
{ 
    for (int i = 0; i < items.Length; i++) 
    { 
     //in this part i cant find the correct syntax 
     if(decodeValue(id, ref items[i], code[i+2])) 
     { 

     } 
    } 

    return false; 
} 

如果你需要在你的代碼項目的類型,只需調用.GetType()的地方actualy需要。這不僅是做事情的好方法,而且在某些情況下性能很有效(編譯器可以大大優化此函數的某些調用)。

+0

謝謝 當你在沒有考慮改變基本設計的情況下添加東西時,會發生這種情況。 而不是適應decodeList decodeValue我應該做的相反。 –

2

仿製藥(<T>)和反思(.GetType())不是好朋友。沒有方便方式來表達。你可以,但是,濫用dynamic做到這一點,你不能輕易使用ref在這種情況下。此外,您不能在objectT之間輸入ref。所以基本上,有很多障礙。坦率地說,我認爲你應該評估decodeValue<T>是否真的需要通用。在這種情況下 - 特別是在使用TypeDescriptor時 - 我非常懷疑它的必要性。我懷疑你最好的選擇是:

private bool DecodeValue(int id, ref object item, Type type, string code) 
+0

該函數以字符串的形式批量解析服務器通信 –

+1

@CedricRaymond我不確定這會改變什麼,如果有的話... ...這不會使泛型好或不適合... –

+0

每個函數都有一個不同的參數集,必須解碼並檢查錯誤 類型可以是int,byte,long,string,bool,DateTime –

0

GetType()的編譯時的泛型語法用於運行時。你不能將它們混合在一起使用。

當您將源代碼轉換爲二進制文件時,將解析泛型類。在該區域使用通用類型中提供的類型或接口。

與此相反,GetType在執行期間返回一個類型。該類型不能插入通用定義中,因爲編譯已經在當時完成。

+0

其實這並不完全正確; IL比你想象的要靈活得多,你提到的所有東西都可以在運行前用不知道的類型來完成。它只是不方便*。例如,您可以使用'MethodInfo.MakeGenericMethod' - 或者更方便的方法,可以使用'dynamic'來獲得運行時間以進行切換。但它是不雅的*,通常意味着你不應該首先這樣做。關鍵在於,在C#中(與Java或C++不同),在編譯期間,泛型類型信息被**保留**;它不會被編譯器 –

+0

刪除,因爲webgl的目標我不能使用反射 這真的很煩人,否則我永遠不會有這個問題 –

相關問題