[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("直接 new 父類"); Parent p = new Parent(); p.Print(); Console.WriteLine("直接 new 子類"); Sub s = new Sub(); s.Print(); Console.WriteLine("父類 new 子類"); Parent p2 = new Sub(); p2.Print(); Console.Read(); } } public class Parent { public void Print() { Console.WriteLine("第 1 種:隨機應變,子就是子父就是父。獲取當前實例的type"); Type t1 = this.GetType(); Console.WriteLine(t1.FullName); Console.WriteLine("第 2 種:一定是父類. 獲取執行方法所在類的type "); Type t2 = new System.Diagnostics.StackTrace().GetFrame(0).GetMethod().DeclaringType; Console.WriteLine(t2.FullName); Console.WriteLine("第 3 種:一定是父類. 獲取執行方法所在類對象的type"); Type t3 = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType; Console.WriteLine(t3.FullName); Console.WriteLine("第 4 種:一定是父類. 獲取聲明該成員的類的type"); Type t4 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType; Console.WriteLine(t3.FullName); Console.WriteLine(); } } public class Sub : Parent { } }