如何在T未知时使用反射</t> </object>,如何执行List <object> .Cast <t>

时间:2009-09-10 16:31:55

标签: c# generics reflection casting

我一直在努力做这个好几个小时,这就是我所拥有的

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

这会让我回头

  

System.Linq.Enumerable + d__aa`1 [MyObjectType]

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

  

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

任何指针都会很棒

1 个答案:

答案 0 :(得分:17)

之后你只需要调用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 });
}
相关问题