C#——父类中的this的指向,及用反射获取当前类所在的Type
[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
{
}
}
补充:软件开发 , C# ,