我想發送一個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循環中,但我認爲有一種更優雅的方式。有什麼建議麼?
也不起作用 if(decodeValue(id,ref items [i],code [i + 2])) –
爲什麼你首先需要'T'?你的代碼看起來像你可以只使用'ref object item' – Nico
,因爲我首先製作了decodeValue,之後我對自己說,這樣做會更好,因此我添加了decodeValues並嘗試將其調整爲decodeValue。 decodeValue起初是一個很好的使用模板,因爲我發送的每個消息的硬編碼一個接一個。 –