为了生产
List<T>
类型,因此是实例,在运行时,其中t来自
Type
对象(即在编译时不知道),您可以这样做:
Type genericListType = typeof(List<>); // yes, this really is legal syntax
Type elementType = ...
Type specificListType = genericListType.MakeGenericType(elementType);
// specificListType now corresponds to List<T> where T is the same type
// as elementType
IList list = (IList)Activator.CreateInstance(specificListType);
这将在运行时生成正确的列表类型并将其存储在
list
变量。
请注意,无法让编译器推断变量类型,因此:
var list = Loader.Load(...)
仍然不会产生
列表& T;
类型
,它必须使用编译时已知的非泛型类型来存储列表,例如
IList
,但是您存储在其中的对象可以是一个通用对象,按照我上面描述的方式生成。