温馨提示×

C#中typeof关键字如何用于泛型编程

c#
小樊
92
2024-08-12 05:20:33
栏目: 编程语言

在C#中,typeof关键字通常用于获取指定类型的Type对象。在泛型编程中,可以使用typeof关键字来获取泛型类型的Type对象。例如:

public class GenericClass<T>
{
    public void PrintType()
    {
        Type type = typeof(T);
        Console.WriteLine("Type of T is: " + type);
    }
}

class Program
{
    static void Main()
    {
        GenericClass<int> genericClass = new GenericClass<int>();
        genericClass.PrintType(); // 输出:Type of T is: System.Int32
    }
}

在上面的示例中,我们定义了一个泛型类GenericClass,然后在PrintType()方法中使用typeof关键字获取T类型的Type对象,并输出到控制台。在Main()方法中,我们实例化了GenericClass类,并调用PrintType()方法打印T的类型。

0