c# - 如何在 C# 中调用动态类型的泛型方法

标签 c# reflection types

我有以下代码:

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/

相关文章:

c# - 观察者模式还是只是创建事件处理?

c# - ListView 光标变化和闪烁

.net - StackFrame.GetNativeOffset()有什么用?

types - 经典 ASP 类型不匹配

c++ - 错误: '.' token 之前应有预期的unqualified-id

c++ - 将 std::string 转换为 const char*,出现错误

c# - PropertyBuilder<T> 不包含 HasColumnType 的定义

c# - 如何找到集合中的下一个最大键?

java - ExceptionInInitializerError : code size limit exceeded when loading a DLL in JNA

java - 在 Java 中使用共享接口(interface)迭代枚举(类对象)