是否有可能在运行时动态设置T类型,并创建一个新的List<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的协变特性可以帮助你,并允许你将变量声明为,那是不可能的,因为T被List用于in和out两个目的。)
请注意,为了访问“未构造”的通用类型,使用了不寻常的List<>语法。
public static System.Collections.IList ConstructGenericList(Type t)
{
return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));
}
IList<SomeSuperType>
。我来改正一下。 - Jason Kresowaty对于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>();
}