创建变量类型列表

我正在尝试创建某种类型的列表。

我想使用List符号,但我所知道的只是一个“System.Type”

类型a具有可变性。 如何创建变量类型列表?

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

public IList createListOfMyType(Type myType) { return new List(); } 

您可以使用Reflections,这是一个示例:

  Type mytype = typeof (int); Type listGenericType = typeof (List<>); Type list = listGenericType.MakeGenericType(mytype); ConstructorInfo ci = list.GetConstructor(new Type[] {}); List listInt = (List)ci.Invoke(new object[] {}); 

这样的事情应该有效。

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

谢谢! 这是一个很大的帮助。 这是我对Entity Framework的实现:

  public System.Collections.IList TableData(string tableName, ref IList 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); }