我正在尝试使用通用的List<T>
自定义类MyList<T>
来进行自动项解析,而我却坚持创建一个MyList<T>
的返回类型。具体来说,我不知道如何使用给定的类型创建这样的列表。我能做的一件事就是找出类型并将其存储在Type itemType
变量中。
This question帮助我找出了列表项的类型。
问题是我在运行时之前不知道列表类型,因此无法在代码中明确写入。
如何使用Type itemType
变量创建特定类型的项目列表?
答案 0 :(得分:2)
您可以使用Reflection执行此操作,例如:
var listType = typeof(List<>);
listType.MakeGenericType(typeof(MyType))
return Activator.CreateInstance(listType);
另一个例子,如果您拥有的只是“MyType”的一个实例,但在运行时才知道它是什么:
public IEnumerable GetGenericListFor(object myObject){
var listType = typeof(List<>);
listType.MakeGenericType(myObject.GetType())
return Activator.CreateInstance(listType);
}
答案 1 :(得分:0)
Here是关于在给定泛型类型和参数类型的情况下动态创建泛型类型的相应MSDN文章。滚动到中间的“构建通用类型的实例”部分。
快速样本:
Type d1 = typeof(Dictionary<,>);
Type[] typeArgs = {typeof(string), typeof(int)};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);