在C#中,typeof
关键字不能直接用于泛型类型。但是,你可以使用typeof
与泛型类型一起,并在运行时获取泛型类型的实际类型。这里有一个例子:
public class MyGenericClass{ public void PrintType() { Type type = typeof(T); Console.WriteLine($"The type of T is: {type}"); } } public class Program { public static void Main() { MyGenericClass intInstance = new MyGenericClass (); intInstance.PrintType(); // 输出 "The type of T is: System.Int32" MyGenericClass stringInstance = new MyGenericClass (); stringInstance.PrintType(); // 输出 "The type of T is: System.String" } }
在这个例子中,MyGenericClass
是一个泛型类,我们可以通过typeof(T)
获取泛型类型T
的实际类型。在Main
方法中,我们创建了两个MyGenericClass
的实例,分别用int
和string
作为泛型参数,并调用PrintType
方法来打印泛型类型的实际类型。