typeof 和 GetType
typeof 運算符返回作為 System.Type 對象傳遞給它的類的類型。GetType() 方法是相關的,並且返回類或異常的運行時類型。typeof 和 GetType() 都可以與反射一起使用,以動態地查找關於對象的信息,如下面的示例所示:
using System; using System.Reflection; public class Customer { string name; public string Name { set { name = value; } get { return name; } } } public class TypeTest { public static void Main() { Type typeObj = typeof(Customer); Console.WriteLine("The Class name is {0}", typeObj.FullName); // Or use the GetType() method: //Customer obj = new Customer(); //Type typeObj = obj.GetType(); Console.WriteLine("\nThe Class Members\n=================\n "); MemberInfo[] class_members = typeObj.GetMembers(); foreach (MemberInfo members in class_members) { Console.WriteLine(members.ToString()); } Console.WriteLine("\nThe Class Methods\n=================\n"); MethodInfo[] class_methods = typeObj.GetMethods(); foreach (MethodInfo methods in class_methods) { Console.WriteLine(methods.ToString()); } } }
運行此程序,輸出如下:
The Class name is Customer
The Class Members
=================
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void set_Name(System.String)
System.String get_Name()
System.Type GetType()
Void .ctor()
System.String Name
The Class Methods
=================
Int32 GetHashCode()
Boolean Equals(System.Object)
System.String ToString()
Void set_Name(System.String)
System.String get_Name()
System.Type GetType()
這為我們顯示了從 System.Object 繼承的所有類的成員,並且還展示了一種方法,C# 在內部將 get 和 set 屬性 Accessors 表示為 get_xxx() 和 set_xxx() 方法。
在下一個示例中,我們使用 GetType() 在運行時查找表達式的類型:
using System;
public class TypeTest
{
public static void Main()
{
int radius = 8;
Console.WriteLine("Calculated area is = {0}",
radius * radius * System.Math.PI);
Console.WriteLine("The result is of type {0}",
(radius * radius * System.Math.PI).GetType());
}
}
此程序的輸出告訴我們,結果是 System.Double 類型,選擇它是因為System.Math.PI 是這種類型。
Calculated area is = 201.061929829747
The result is of type System.Double