System.Type 物件兩者皆可搭配反射動態查詢物件資訊。
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);
Console.WriteLine("\nThe Class Members\n=================\n");
MemberInfo[] members = typeObj.GetMembers();
foreach (MemberInfo m in members)
Console.WriteLine(m.ToString());
Console.WriteLine("\nThe Class Methods\n=================\n");
MethodInfo[] methods = typeObj.GetMethods();
foreach (MethodInfo m in methods)
Console.WriteLine(m.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()
可見 C# 內部將屬性存取器轉為 get_xxx()/set_xxx() 方法,並繼承 System.Object 成員。
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());
}
}
輸出:
Calculated area is = 201.061929829747
The result is of type System.Double
因 Math.PI 為 double,整個運算結果提升為 double。