2010-03-22 15 views
19

Estoy tratando de crear una lista de cierto tipo.Crear lista de tipo de variable

Quiero usar la notación de lista pero lo único que sé es un "System.Type"

El tipo tienen una es variable. ¿Cómo puedo crear una lista de un tipo de variable?

Quiero algo similar a este código.

public IList createListOfMyType(Type myType) 
{ 
    return new List<myType>(); 
} 
+2

Asegúrese de que no existe un diseño defectuoso, ya que esto huele como uno. – Dykam

Respuesta

14

Usted podría utilizar Reflexiones, aquí es una muestra:

Type mytype = typeof (int); 

    Type listGenericType = typeof (List<>); 

    Type list = listGenericType.MakeGenericType(mytype); 

    ConstructorInfo ci = list.GetConstructor(new Type[] {}); 

    List<int> listInt = (List<int>)ci.Invoke(new object[] {}); 
+0

El problema es que no sabemos myType es typeof (int), por lo que su última declaración no puede ser List , nos gustaría algo como Liar , pero por supuesto que no se puede hacer. Para crear la instancia, debemos usar System.Activator.CreateInstance (myType). Pero, de nuevo, el valor de retorno si un objeto de tipo myType. Y debe usar System.Type para obtener información sobre los métodos/propiedades/interfaces, etc. –

+0

Se puede hacer utilizando genéricos: Lista CreateMyList (). Dentro de este método puedes hacer: Tipo myType = typeof (T); y luego todo lo de arriba Podrías usar un método como este: List list = CreateList () –

33

Algo como esto debería funcionar.

public IList createList(Type myType) 
{ 
    Type genericListType = typeof(List<>).MakeGenericType(myType); 
    return (IList)Activator.CreateInstance(genericListType); 
} 
+0

Gracias, esto resolvió mi problema. – Jan

+0

tuve que jugar con esto un poco antes de que funcionase. Soy totalmente novato en el uso de Type, así que aquí hay un fragmento de código que otras personas pueden encontrar útil al llamar a este método createList desde su Main o algún otro método: string [] words = {"cosas", "cosas" , "wordz", "misc"}; var shtuff = createList (words.GetType()); –

+1

Me doy cuenta de que esto es viejo, pero @Jan, este resolvió tu problema, debería marcarse como respuesta. @kayleeFrye_onDeck también puedes hacer 'typeof (string [])' – 182764125216

0

Gracias! Esta fue una gran ayuda. Aquí está mi aplicación de Entity Framework:

public System.Collections.IList TableData(string tableName, ref IList<string> errors) 
    { 
     System.Collections.IList results = null; 

     using (CRMEntities db = new CRMEntities()) 
     { 
      Type T = db.GetType().GetProperties().Where(w => w.PropertyType.IsGenericType && w.PropertyType.GetGenericTypeDefinition() == typeof(System.Data.Entity.DbSet<>)).Select(s => s.PropertyType.GetGenericArguments()[0]).FirstOrDefault(f => f.Name == tableName); 
      try 
      { 
       results = Utils.CreateList(T); 
       if (T != null) 
       { 
        IQueryable qrySet = db.Set(T).AsQueryable(); 
        foreach (var entry in qrySet) 
        { 
         results.Add(entry); 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       errors = Utils.ReadException(ex); 
      } 
     } 

     return results; 
    } 

    public static System.Collections.IList CreateList(Type myType) 
    { 
     Type genericListType = typeof(List<>).MakeGenericType(myType); 
     return (System.Collections.IList)Activator.CreateInstance(genericListType); 
    } 
Cuestiones relacionadas