Dynamic List<T> type [duplicate]
Is it possible to create a new List<T>
where the T is dynamically set at runtime?
Cheers
It's possible, but not necessarily useful, since you couldn't actually use it from compiled code as strongly typed. The creation code would be
Type myType;
Type listType = typeof(List<>).MakeGenericType(myType);
IList myList = (IList)Activator.CreateInstance(listType);
Yes. You can do this via Reflection, using Type.MakeGenericType and Activator.CreateInstance.
IList MakeListOfType(Type listType)
{
Type listType = typeof(List<>);
Type specificListType = listType.MakeGenericType(listType);
return (IList)Activator.CreateInstance(specificListType);
}
Yes. However, you won't be able to assign it to a variable that has a generic type since the T in this case will not be decided until runtime. (If you are thinking that the .NET 4.0 covariance feature will help you and let you declare the variable as IList<SomeSuperType>
, it won't as the T
is used by List<T>
for both in
and out
purposes.)
Note the unusual List<> syntax in order to access the "unconstructed" generic type.
public static System.Collections.IList ConstructGenericList(Type t)
{
return (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(t));
}
For DataContractSerializer Known Types you may want to supply not only types from your assembly but also list of that types:
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;
}
yes using generic you can do something like this
var asd = METHOD<Button>();
List<t> METHOD<t>()
{
return new List<t>();
}
精彩评论