阅读量:3
在C#中,typeof关键字不能直接用于泛型类型。但是,你可以使用typeof与泛型类型一起,并在运行时获取泛型类型的实际类型。这里有一个例子:
public class MyGenericClass<T>
{
public void PrintType()
{
Type type = typeof(T);
Console.WriteLine($"The type of T is: {type}");
}
}
public class Program
{
public static void Main()
{
MyGenericClass<int> intInstance = new MyGenericClass<int>();
intInstance.PrintType(); // 输出 "The type of T is: System.Int32"
MyGenericClass<string> stringInstance = new MyGenericClass<string>();
stringInstance.PrintType(); // 输出 "The type of T is: System.String"
}
}
在这个例子中,MyGenericClass是一个泛型类,我们可以通过typeof(T)获取泛型类型T的实际类型。在Main方法中,我们创建了两个MyGenericClass的实例,分别用int和string作为泛型参数,并调用PrintType方法来打印泛型类型的实际类型。
以上就是关于“c# typeof能用于泛型类型吗”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm