C#基础语法 の 反射



1.反射定义

一个运行的程序,查看本身的元素或其他类型的元数据的行为叫做反射

MVC、IOC、ORM、AOP 这些都用到反射。



2.简单的例子

 class BaseClass
    {
        public int BaseField = 0;
    }
 class DerivedClass:BaseClass
    {
        public int DerviedField = 0;
    }
 static void Main(string[] args)
        {
            BaseClass bc = new BaseClass();
            var dc = new DerivedClass();
            BaseClass[] bca = new BaseClass[] { bc, dc };
            foreach (var v in bca)
            {
                Type t = v.GetType();
                Console.WriteLine($"Object type:{t.Name}");


                FieldInfo[] fi = t.GetFields();
                foreach (var f in fi)
                {
                    Console.WriteLine($"File :{f.Name}");
                }
                Console.WriteLine();
            }
        }

输出结果:

Object type:BaseClass
File :BaseField

Object type:DerivedClass
File :DerviedField
File :BaseField




3.常用的 Type 成员

成员成员类型描述
Name属性返回类型的名字
Namespace属性返回类型的命名空间
Assembly属性返回声明类型的数据集
GetFields方法返回类型的字段列表
GetProperties方法返回类型的属性列表
GetMethods方法返回类型的方法列表



4.对 dll 文件使用反射

4.1 dll 文件的读取

通过程序集名称返回Assembly对象
        Assembly ass = Assembly.Load("ClassLibrary831");
        
通过DLL文件名称返回Assembly对象
        Assembly ass = Assembly.LoadFrom("ClassLibrary831.dll");
        
通过Assembly获取程序集中类 
        Type t = ass.GetType("ClassLibrary831.NewClass");   //参数必须是类的全名
        
通过Assembly获取程序集中所有的类
        Type[] t = ass.GetTypes();


4.2 具体的例子

1. 目录结构

在这里插入图片描述
2.代码

 static void Main(string[] args)
        {
            // 加载 DLL 文件
            // 这个是直接动态加载
            Assembly assembly = Assembly.Load("LibA");
            // 和上面的区别是这个得用 dll 文件
            Assembly assembly1 = Assembly.LoadFrom("LibA.dll");
            // 用绝对路径引入
            Assembly assembly2 = Assembly.LoadFile("D:/Desktop/test01/ConsoleApp3/LibA/bin/Debug/netstandard2.0/LibA.dll");

            var Tpye = assembly2;
            Console.WriteLine(Tpye.FullName);

            // 获取类型(这一步要在获得 Dll 文件的基础上进行)
            
            Type type = assembly.GetType("LibA.Class1");
            object o = Activator.CreateInstance(type);// 必须是个type类型,简单点说,必须是个类。
            Console.WriteLine(type.Name);

            // 用接口做强制规范,然他能 “点“ 出来
            IAClasscs rel = type as IAClasscs;
            rel.GetName();

            //object mm = Activator.CreateInstance(type);


参考文献

[1]https://www.cnblogs.com/Stephenchao/p/4481995.html
[2]https://www.bilibili.com/video/BV1hk4y1r7PZ

posted @ 2020-12-24 22:05  沧海一声笑rush  阅读(49)  评论(0编辑  收藏  举报