C#——父类中的this的指向,及用反射获取当前类所在的Type

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
    {
        
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值