2011-01-11 11 views
34

¿Es posible crear un objeto genérico de un tipo reflejado en C# (.Net 2.0)?C# ejemplifican lista genérica de tipo reflejada

void foobar(Type t){ 
    IList<t> newList = new List<t>(); //this doesn't work 
    //... 
} 

el tipo, t, no se conoce hasta tiempo de ejecución.

+0

¿Qué esperas hacer con una lista que no conoces el tipo de en tiempo de compilación? – dtb

+1

¿Es capaz de escribir esto como una función genérica, como en 'foobar vacío () {IList newList = nueva lista (); } ' – Juliet

+1

Tengo la sensación de que esto podría ser un olor código, como resultado de hacer frente a un problema mayor en el mal sentido. –

Respuesta

102

Prueba esto:

void foobar(Type t) 
{ 
    var listType = typeof(List<>); 
    var constructedListType = listType.MakeGenericType(t); 

    var instance = Activator.CreateInstance(constructedListType); 
} 

Ahora qué hacer con instance? Puesto que usted no sabe el tipo de contenido de su lista, probablemente lo mejor que podría hacer sería para echar instance como IList por lo que podría tener algo más que una simple object:

// Now you have a list - it isn't strongly typed but at least you 
// can work with it and use it to some degree. 
var instance = (IList)Activator.CreateInstance(constructedListType); 
+6

+1 para 'typeof (Lista <>)', I no había visto esto antes –

+0

¿'var' existe en .Net framework 2.0 ?! –

+0

@sprocketonline: 'var' es una característica de C# 3 por lo que si usted está usando C# 2 tendrá que declarar las variables explícitamente. –

0

Usted puede utilizar MakeGenericType para tales operaciones.

Para la documentación, ver here y here.

6
static void Main(string[] args) 
{ 
    IList list = foobar(typeof(string)); 
    list.Add("foo"); 
    list.Add("bar"); 
    foreach (string s in list) 
    Console.WriteLine(s); 
    Console.ReadKey(); 
} 

private static IList foobar(Type t) 
{ 
    var listType = typeof(List<>); 
    var constructedListType = listType.MakeGenericType(t); 
    var instance = Activator.CreateInstance(constructedListType); 
    return (IList)instance; 
} 
+0

+1 para recordar las buenas viejas interfaces no genéricas compatibles :) – leppie

Cuestiones relacionadas