动态列表类型
是否可以创建一个新的List
,其中T是在运行时动态设置的?
干杯
它是可能的,但不一定有用,因为你实际上不能像强类型那样在编译代码中使用它。 创建代码将是
Type myType; Type listType = typeof(List<>).MakeGenericType(myType); IList myList = (IList)Activator.CreateInstance(listType);
是。 您可以使用Type.MakeGenericType和Activator.CreateInstance通过Reflection执行此操作。
IList MakeListOfType(Type listType) { Type listType = typeof(List<>); Type specificListType = listType.MakeGenericType(listType); return (IList)Activator.CreateInstance(specificListType); }
是。 但是,您将无法将其分配给具有generics类型的变量,因为在这种情况下T将在运行时之前不会被确定。 (如果您认为.NET 4.0协方差function可以帮助您并让您将变量声明为IList
,那么它不会因为List
用于out
目的而使用。)
请注意不常见的List <>语法,以便访问“未构造”的泛型类型。
public static System.Collections.IList ConstructGenericList(Type t) { return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t)); }
对于DataContractSerializer已知类型,您可能不仅要提供程序集中的类型,还要提供这些类型的列表:
public static List GetKnownTypesForDataContractSerializer() { Assembly a = Assembly.GetExecutingAssembly(); Type[] array = a.GetExportedTypes(); List lista = array.ToList(); lista = lista.FindAll(item => ((item.IsClass || item.IsEnum) & !item.IsGenericType & !item.IsAbstract == true)); List withEnumerable = new List (); foreach (Type t in lista) { withEnumerable.Add(t); //add basic type //now create List<> type Type listType = typeof(List<>); var listOfType = listType.MakeGenericType(t); withEnumerable.Add(listOfType); //add Type of List } return withEnumerable; }
是的使用generics你可以做这样的事情
var asd = METHOD