C# Reflection笔记

反射

1. 程序集里的元数据

C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64\ildasm.exe
用这个工具打开一个assembly。
file -> dump -> dump metainfo, 保存到dump.txt中, 看这个文件。
编译生成il代码,和类的metainfo。

AppDomain

一个程序运行起来以后,有一个AppDomain,在这个AppDomain中放了我们用到的所有assembly。

需要using System.Reflection;

Assembly的组成


2. 反射

反射概念:

在程序运行时,动态获取 程序集, 类型(class,interface)和类型的成员信息(方法,字段,属性等)。
在程序运行时,动态创建 类型实例, 以及调用和方法 动态创建出来的 类型实例的成员。
反射的应用:框架(Spring .net/ .Net MVC等)
在程序运行时,动态获取 程序集:

    class Program
    {
        static void Main(string[] args)
        {
            Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
            Person p = new Person();
            p.TestAssembly();
        }
    }


    class Person {
        public String Name { get; set; }
        public int Age { get; set; }
        private int id;

        public void TestAssembly() {
            Assembly ass = this.GetType().Assembly;
            Type[] types = ass.GetTypes();
            Type currentType = ass.GetType();
            //根据类的full name,获取在内存中的类型对象
            Type typeByFullName = ass.GetType("ConsoleApplication6.Person");


            Type type = this.GetType();
            MethodInfo[] methods = this.GetType().GetMethods();
            this.GetType().GetMembers();
            this.GetType().GetMember("Name");
            FieldInfo field =  type.GetField("id");
            PropertyInfo prop = type.GetProperty("Name");


        }
    }
在程序运行时,动态创建 类型实例:在Person类中加下面4个方法,在Main中测试
        public void CreatePersonObject() {
            Type type = this.GetType();
            //使用Person类的Type对象,创建一个Person对象
            Person p = Activator.CreateInstance(type) as Person;
            Person p1 = Activator.CreateInstance<Person>();

            //使用Person类的Name属性对象,为p的Name属性赋值
            PropertyInfo prop = type.GetProperty("Name");
            prop.SetValue(p1, "toto");
            Console.WriteLine(p1.Name);

            //使用Person类的Sayhi方法对象,调用p1的Sayhi方法
            MethodInfo method = type.GetMethod("Sayhi");
            method.Invoke(p1, null);
            MethodInfo method1 = type.GetMethod("ShowNumber");
            object[] arrParams = {2};
            method1.Invoke(p1, arrParams);
            MethodInfo method2 = type.GetMethod(&#
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值