我有一个类型对象typeof(List<T>)
,但我需要的是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));
var t = typeof(List<string>);
var t2 = t.GetGenericTypeDefinition();
然后可以这样做:
var t = typeof(List<>);
var t2 = t.MakeGenericType(typeof(string));