温馨提示×

c# typeof能用于泛型类型吗

c#
小樊
94
2024-11-16 21:35:51
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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<T>是一个泛型类,我们可以通过typeof(T)获取泛型类型T的实际类型。在Main方法中,我们创建了两个MyGenericClass的实例,分别用intstring作为泛型参数,并调用PrintType方法来打印泛型类型的实际类型。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:typeof c#在C#编程中的重要性

0