【发布时间】:2011-02-22 06:21:20
【问题描述】:
我一直在寻找这个。我想知道如何获取传递给创建列表的模板类型。例如。
List<string> listOfStrings = new List<string>();
如何从中获取字符串类型?我知道如何使用类型来获取字段并找到列表类型,但不知道其中的模板。
【问题讨论】:
标签: c# templates reflection types
我一直在寻找这个。我想知道如何获取传递给创建列表的模板类型。例如。
List<string> listOfStrings = new List<string>();
如何从中获取字符串类型?我知道如何使用类型来获取字段并找到列表类型,但不知道其中的模板。
【问题讨论】:
标签: c# templates reflection types
在这种情况下,你可以这样得到它
Type genericType = listOfStrings.GetType().GetGenericArguments()[0];
注意,如果你在非泛型类型上尝试这个,它会失败,因为 GetGenericArguments 数组的长度将为 0,但你当然可以采取措施来控制数组的长度。
【讨论】:
您是在谈论获取存储在此列表中的项目类型吗?
listOfStrings[0].GetType()
将返回类型。
编辑:
这是正确的解决方案:
Type type = listOfStrings.GetType();
Type itemType = type.GetGenericArguments()[0];
【讨论】:
但也许他想知道在调用函数时如何获取 T...
void MyFunc<T>(List<T> list) {
/// T is the type passed to the List<T>, so for a List<int>, T is int
T element = default(T);
list.Add(element);
}
【讨论】:
How would I get the string type from this? 的问题部分。您无法从任何地方获取类型字符串。我认为这里没有反射的方法。