C# 如何执行列表<;对象>;。铸造<;T>;当T未知时使用反射

C# 如何执行列表<;对象>;。铸造<;T>;当T未知时使用反射,c#,generics,reflection,casting,C#,Generics,Reflection,Casting,我已经试着做了好几个小时了,这是我所能做的 var castItems = typeof(Enumerable).GetMethod("Cast") .MakeGenericMethod(new Type[] { targetType }) .Invoke(null, new object[] { items }); 这是我的回报 System.Linq.Enumerable+d_uaa`1[MyObject Type]

我已经试着做了好几个小时了,这是我所能做的

var castItems = typeof(Enumerable).GetMethod("Cast")
                  .MakeGenericMethod(new Type[] { targetType })
                  .Invoke(null, new object[] { items });
这是我的回报

System.Linq.Enumerable+d_uaa`1[MyObject Type]

而我需要(对于我的ViewData)作为通用列表,即

System.Collections.Generic.List`1[MyObjectType]


任何指针都很好

您只需在之后调用ToList():

static readonly MethodInfo CastMethod = typeof(Enumerable).GetMethod("Cast");
static readonly MethodInfo ToListMethod = typeof(Enumerable).GetMethod("ToList");

...

var castItems = CastMethod.MakeGenericMethod(new Type[] { targetType })
                          .Invoke(null, new object[] { items });
var list = ToListMethod.MakeGenericMethod(new Type[] { targetType })
                          .Invoke(null, new object[] { castItems });
另一种选择是在您自己的类中编写一个泛型方法来完成此操作,并使用反射调用该方法:

private static List<T> CastAndList(IEnumerable items)
{
    return items.Cast<T>().ToList();
}

private static readonly MethodInfo CastAndListMethod = 
    typeof(YourType).GetMethod("CastAndList", 
                               BindingFlags.Static | BindingFlags.NonPublic);

public static object CastAndList(object items, Type targetType)
{
    return CastAndListMethod.MakeGenericMethod(new[] { targetType })
                            .Invoke(null, new[] { items });
}
私有静态列表CastAndList(IEnumerable项)
{
return items.Cast().ToList();
}
私有静态只读方法信息CastAndListMethod=
typeof(YourType).GetMethod(“CastAndList”,
BindingFlags.Static | BindingFlags.NonPublic);
公共静态对象CastAndList(对象项,类型targetType)
{
返回CastAndListMethod.MakeGenericMethod(新[]{targetType})
.Invoke(null,新[]{items});
}

Thank完全忘记了(代码盲)Thank。[顺便说一句,您的方法中有一个输入错误,任何想要复制任何粘贴的人都应该说var list=ToListMethod.MakeGen….]太棒了。很难找到,但完全解决了我的问题。谢谢大家。