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

avatar
作者
猴君
阅读量:0

在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的类型。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!