I need to create a generic type, but I do not know the type at compile time. I would like to do this:
Type t = typeof(whatever);
var list = new List<t>
this won't compile, because t is not a valid type. But it does know all about a valid type. Is there a way to dynamically create the generic list from a System.Type like this? I may need reflection, and that's ok, I am just a bit lost here.
Like this:
Type t;
Type genericListType = typeof(List<>).MakeGenericType(t);
object list = Activator.CreateInstance(genericListType);
Note that you can only assign it to a variable of type object
. (Although you can cast to to the non-generic IList
interface)
To use the list
variable, you'll probably need reflection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.