在C#中,你可以使用typeof
关键字来获取一个类型的信息。typeof
是一个运算符,它返回一个System.Type
对象,该对象表示指定的类型。以下是一些使用typeof
的示例:
using System; class Program { static void Main() { // 获取内置类型的信息 Type intType = typeof(int); Type doubleType = typeof(double); Type stringType = typeof(string); // 获取自定义类型的信息 Type myCustomType = typeof(MyCustomClass); // 输出类型信息 Console.WriteLine($"Type of int: {intType}"); Console.WriteLine($"Type of double: {doubleType}"); Console.WriteLine($"Type of string: {stringType}"); Console.WriteLine($"Type of MyCustomClass: {myCustomType}"); } } class MyCustomClass { // 自定义类的定义 }
在这个示例中,我们首先获取了一些内置类型(如int
、double
和string
)的信息,然后获取了一个自定义类型(MyCustomClass
)的信息。最后,我们将这些类型信息输出到控制台。