如何通过移除泛型参数从typeof(List < T >)获取typeof(List<> )?

3

我有一个类型对象typeof(List<T>),但我需要的是typeof(List<>),以便我可以使用MakeGenericType()来检索List的类型对象,这可行吗?

更新: 那些回答我的人,谢谢。这似乎是一个微不足道的问题。但无论如何,我向所有人投了赞成票,并接受了第一个答案。


1
你看过这个吗? - Uthistran Selvaraj
4个回答

4

如果我正确理解了你的问题,你有一个通用类型(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>

3

1

我猜你的意思是要实现类似下面这样的东西?

var list = new List<int>();
Type intListType = list.GetType();
Type genericListType = intListType.GetGenericTypeDefinition();
Type objectListType = genericListType.MakeGenericType(typeof(object));

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接