【发布时间】:2012-12-26 10:04:14
【问题描述】:
我有 typeof(List<T>) 作为 Type 对象,但我需要 typeof(List<>) 可以从中使用 MakeGenericType() 检索 List 的类型对象,这可能吗?
更新:伙计们,谢谢。这似乎是一个微不足道的问题。但无论如何,我赞成每个人并接受第一个答案。
【问题讨论】:
我有 typeof(List<T>) 作为 Type 对象,但我需要 typeof(List<>) 可以从中使用 MakeGenericType() 检索 List 的类型对象,这可能吗?
更新:伙计们,谢谢。这似乎是一个微不足道的问题。但无论如何,我赞成每个人并接受第一个答案。
【问题讨论】:
如果我正确地理解了您的问题,您有一个泛型类型 (List<int>) 和另一种类型(比如说long),并且您想要创建一个List<long>。可以这样做:
Type startType = listInt.GetType(); // List<int>
Type genericType = startType.GetGenericTypeDefinition() //List<T>
Type targetType = genericType.MakeGenericType(secondType) // List<long>
但是,如果您使用的类型确实是列表,那么如果您实际使用它可能会更清楚:
Type targetType = typeof(List<>).MakeGenericType(secondType) // List<long>
【讨论】:
【讨论】:
我假设您的意思是实现以下目标?
var list = new List<int>();
Type intListType = list.GetType();
Type genericListType = intListType.GetGenericTypeDefinition();
Type objectListType = genericListType.MakeGenericType(typeof(object));
【讨论】:
答案是 Type.GetGenericTypeDefinition:
http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx
例子:
var t = typeof(List<string>);
var t2 = t.GetGenericTypeDefinition();
然后可以这样做:
var t = typeof(List<>);
var t2 = t.MakeGenericType(typeof(string));
【讨论】: