【发布时间】:2011-01-29 06:26:55
【问题描述】:
是否可以创建一个新的List<T>,其中 T 在运行时动态设置?
干杯
【问题讨论】:
是否可以创建一个新的List<T>,其中 T 在运行时动态设置?
干杯
【问题讨论】:
这是可能的,但不一定有用,因为您实际上无法从编译代码中将其用作强类型。创建代码将是
Type myType;
Type listType = typeof(List<>).MakeGenericType(myType);
IList myList = (IList)Activator.CreateInstance(listType);
【讨论】:
是的。您可以通过反射,使用Type.MakeGenericType 和Activator.CreateInstance 来做到这一点。
IList MakeListOfType(Type listType)
{
Type listType = typeof(List<>);
Type specificListType = listType.MakeGenericType(listType);
return (IList)Activator.CreateInstance(specificListType);
}
【讨论】:
是的。但是,您将无法将其分配给具有泛型类型的变量,因为在这种情况下,T 直到运行时才会确定。 (如果您认为 .NET 4.0 协方差特性会对您有所帮助,并让您将变量声明为 IList<SomeSuperType>,则它不会因为 List<T> 对 in 和 out 都使用 T目的。)
注意不寻常的 List 语法,以便访问“未构造的”泛型类型。
public static System.Collections.IList ConstructGenericList(Type t)
{
return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));
}
【讨论】:
IList<SomeSuperType>。修复。
对于 DataContractSerializer 已知类型,您可能不仅需要提供程序集中的类型,还需要提供这些类型的列表:
public static List<Type> GetKnownTypesForDataContractSerializer()
{
Assembly a = Assembly.GetExecutingAssembly();
Type[] array = a.GetExportedTypes();
List<Type> lista = array.ToList();
lista = lista.FindAll(item => ((item.IsClass || item.IsEnum) & !item.IsGenericType & !item.IsAbstract == true));
List<Type> withEnumerable = new List<Type>();
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<basic type>
}
return withEnumerable;
}
【讨论】:
是的,使用泛型你可以做这样的事情
var asd = METHOD<Button>();
List<t> METHOD<t>()
{
return new List<t>();
}
【讨论】: