我有一些代码如下所示。我想知道是否有可能为传递给 DoSomething 函数的泛型类型获取一个 Type 对象。我意识到 T 是一个类型参数,但我如何将它变成一个类型对象。 dosomething 函数位于我想知道列表对象使用的基础类型的类中。
[STAThread]
static void Main(string[] args)
{
List<string> stringList = new List<string>();
DoSomething(stringList);
}
public void DoSomething<T>(List<T> collection)
{
//Type myType = T; ??!!?
//do something here with the list.
}
最佳答案
只需使用:
Type type = typeof(T);
泛型参数与任何其他类型一样,除非您在编译时不知道该类型到底是什么,因此假定它是符合给定类型约束的对象层次结构中的最上层(对于没有约束的 System.对象)。
关于c# - 泛型类型参数和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1728091/