我有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>
关于c# - 如何通过删除通用参数从 typeof(List<T>) 获取 typeof(List<>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14038969/