2010-03-22 59 views
19

我想创建一个特定类型的列表。创建变量类型列表

我想用列表格式,但我所知道的是一个“System.Type的”

的类型有是可变的。我如何创建一个变量类型的列表?

我想要类似于此代码的东西。

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

确保没有错误的设计,因为这是一个整体。 – Dykam 2010-03-22 15:32:10

回答

14

你可以使用思考,这里是一个示例:

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

问题是我们不知道myType是typeof(int),所以你最后的语句不能是列表,我们想要像骗子这样的东西,但当然这是不能做到的。要创建实例,我们应该使用System.Activator.CreateInstance(myType)。但是,如果myType类型的对象返回值。并且您必须使用System.Type来了解方法/属性/接口等。 – 2013-09-11 14:22:26

+0

可以使用泛型来完成:列表 CreateMyList ()。在这个方法里面你可以这样做:输入myType = typeof(T);然后一切如上。你将能够使用这样的方法:列表 list = CreateList () – 2013-09-11 22:30:19

33

这样的事情应该工作。

​​
+0

谢谢,这解决了我的问题。 – Jan 2010-03-23 07:20:06

+0

在我开始工作之前,我不得不摆弄这一点。我是一个使用Type的新手,所以这里有一个代码片断,其他人可能会从你的Main或其他方法调用此createList方法时找到有用的代码片段: string [] words = {“stuff”,“things” ,“wordz”,“misc”}; var shtuff = createList(words.GetType()); – 2015-02-04 17:28:10

+1

我意识到这是旧的,但@Jan,它解决了你的问题,它应该被标记为答案。 @kayleeFrye_onDeck你也可以'typeof(string [])' – 182764125216 2016-08-12 20:44:38

0

谢谢!这是一个很大的帮助。这里是我对实体框架的实现:

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