2009-09-10 9 views
10

que he estado tratando de hacer esto durante unas cuantas horas ahora y esto es por lo que yo he conseguido¿Cómo puedo realizar una lista <object> .Cast <T> utilizando la reflexión cuando T es desconocida

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

Este me devuelve

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

mientras que necesito (para mi ViewData) como lista genérica es decir,

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

Cualquier punteros sería grande

Respuesta

17

Sólo tiene que llamar ToList() sobre ella después:

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 }); 

Otra opción sería escribir un único método genérico en su propia clase para hacer esto, y llamar al que con la reflexión:

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 }); 
} 
+0

Gracias olvidé por completo que (el código de ceguera se había establecido) gracias. [por cierto, hay un error tipográfico en su método para cualquiera que quiera copiar cualquier pegar debería decir var list = ToListMethod.MakeGen .....] –

+0

He corregido el error tipográfico. –

+0

Brillante. Difícil de encontrar, pero resolvió totalmente mi problema. Gracias a todos. –

Cuestiones relacionadas