[英]How to pass params object[i] to a template function in C#
我正在嘗試將params object [i]發送到T函數,但是找不到正確的語法。
這是一個示例,顯示我要實現的目標的上下文:
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]
無論我嘗試使用哪種語法,編譯器都告訴我在>
之后需要a )
我可以將函數decodeValue內聯到for循環中,但是我認為有一種更優雅的方法。 有什么建議么?
在您的示例中,您替換了項目的內容。 為什么甚至需要模板化功能? 只要這樣做:
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()。 這不僅是做事的好方法,而且在某些情況下可以提高性能(編譯器可以極大地優化此函數的某些調用)。
泛型( <T>
)和反射( .GetType()
)不是好朋友。 沒有方便的表達方式。 你可以 ,但是,濫用dynamic
做到這一點, 但你不能輕易使用ref
在這種情況下。 此外,您不能在object
和T
之間進行ref
。 所以基本上,有很多障礙。 坦白說,我認為您應該評估一下是否確實需要使用decodeValue<T>
。 在這種情況下-特別是在使用TypeDescriptor
-我非常懷疑它是否需要。 我懷疑您最好的選擇是:
private bool DecodeValue(int id, ref object item, Type type, string code)
如果GetType()用於運行時,則泛型語法用於編譯時。 您不能將它們混合使用。
將源轉換為二進制時,將解析通用類。 該區域使用通用類型提供的類型或接口。
相反,GetType在執行期間返回一個類型。 不能在通用定義中插入該類型,因為那時已經完成了編譯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.