我有以下代码:
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.
如何在递归中指定类型,动态泛型类型的语法似乎并不那么简单。
最佳答案
在您的案例中,我没有看到泛型的有效用例。泛型的使用假定您能够在编译时静态地识别类型(或者至少是它的祖先)。你为什么不接受非泛型 IEnumerable
?如果您确实需要在 data
中提供一些基本类型的项目,则将其作为参数提供:
public static List<object[]> Serialise2D_Rec(IEnumerable data, Type t)
{
…
for (…)
{
if (…)
{
}
else
{
…
List<object[]> serialisedProp = Serialise2D_Rec(lst, proptype);
}
}
}
旁注:使用扩展方法 data.Count()
而不是 foreach (var item in data) numElts++;
。
关于c# - 如何在 C# 中调用动态类型的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387693/