我有以下代码:
public static List<object[]> Serialise2D_Rec<T>(IEnumerable<T> data)
{
int numElts = 0;
foreach (var item in data)
numElts++;
Type t = typeof(T); // Get type pointer
PropertyInfo[] propList = t.GetProperties();
List<object[]> toret = new List<object[]>();
for (long propID = 0; propID < propList.Count(); ++propID)
{
var proptype = propList[propID].PropertyType;
if (proptype.IsPrimitive || proptype == typeof(Decimal) || proptype == typeof(String))
{
toret.Add(new object[numElts + 1]);
toret[toret.Count - 1][0] = propList[propID].Name;
int row = 1;
foreach (T item in data)
{
toret[toret.Count - 1][row] = propList[propID].GetValue(item, null);
row++;
}
}
else
{
var lst = (IList)Activator.CreateInstance((typeof(List<>).MakeGenericType(proptype)));
foreach (T item in data)
{
lst.Add(propList[propID].GetValue(item, null));
}
List<object[]> serialisedProp = Serialise2D_Rec(lst);
}
}
return toret;
}
但是,此行将失败并显示以下内容:
List<object[]> serialisedProp = Serialise2D_Rec(lst);
与错误:
****: error CS0411: The type arguments for method '****.****.Serialise2D_Rec<T>(System.Collections.Generic.IEnumerable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
我如何在递归中指定类型,似乎动态泛型类型的语法不是那么简单。
由于您的类型是动态的,因此直到运行时您才知道泛型参数的类型。因此,您还必须将函数视为动态函数,因为直到运行时您才知道函数的通用签名的“类型”。
您必须使用反射来动态调用泛型函数。请参阅如何使用反射调用泛型方法?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句