.NET reflection learning summary 1

Diagram of program operation:

Before understanding reflection, first understand the execution process of the program, as shown in the following figure:

The programmer writes high-level languages ​​(c#, vb, etc.), after being compiled by a compiler, a DLL or EXE file is generated, which is compiled into machine code by JIT, and finally executed by the computer.

If subdivided, the DLL/EXE file contains metadata and intermediate language, which is compiled into machine code by JIT.

Metadata can be understood as a data list. When the CLR executes a DLL/EXE, it first searches for the metadata. The metadata describes the detailed information of the DLL/EXE, such as which namespaces are included, which classes are in the namespace, and the classes in the What are the methods and what properties are there.

 

Reflection concept:

Reflection: System.Reflection is a helper library provided by .Net Framework, which can read and use meatdata (metadata).

 

First experience of reflection:

In the .net code, if you want to load a custom class library, you need three steps: the first step is to add a reference to the class library in the project, the second step is to use the namespace of the class library in the code, and the third step is to call The method of the class library.

If you want to use reflection to achieve this step, you do not need to add a reference step, you can directly load the assembly into the memory, and you can read the information inside. As shown in the following example:

Customize an interface:

namespace DB.Interface
{
    /// <summary>
    /// 数据访问类
    /// </summary>
    public interface IDBHelper
    {
        void Query();
    }
}

Customize a MySql class:

using DB.Interface;
using System;

namespace DB.MySql
{
    public class MySqlHelper : IDBHelper
    {
        public void Query()
        {
            Console.WriteLine("{0}.Query", this.GetType().Name);
        }

        public MySqlHelper()
        {
            Console.WriteLine("{0}被构造", this.GetType().Name);
        }
    }
}

The main method of the program: 

using DB.MySql;
using System;
using System.Reflection;

namespace MyReflection
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("***********************常规用法************************");
                MySqlHelper mySqlHelper = new MySqlHelper();
                mySqlHelper.Query();



                Console.WriteLine("***********************反射用法************************");
                //将dll加载到内存中
                Assembly assembly = Assembly.Load("DB.MySql");//程序集的名称

                foreach (var type in assembly.GetTypes())
                {
                    Console.WriteLine("第一次循环:" + type.Name);

                    foreach (var method in type.GetMethods())
                    {
                        Console.WriteLine(method.Name);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.Read();
        }
    }
}

The program uses conventional writing and reflection writing to print out the name of the instance and the name of the method, respectively, and the running results are as follows:

 All printed out the class name of MySqlHelper, as well as the name of the Query method.

In the reflection example, the names of methods such as ToString are also printed, which are actually methods of Object.

 

Reflective use:

The role of reflection is not only to view the contents of the assembly, it can also use the assembly, that is, you can call methods and so on.

Type type = assembly.GetType("DB.MySql.MySqlHelper");//获取类型
dynamic dDBHelper= Activator.CreateInstance(type);//创建对象
dDBHelper.Query();//调用对象的方法

The execution result is shown in the figure:

 You can call the method in the instance like a regular reference method.

The steps can be divided into: 1. Get the assembly type 2. Create the object 3. Call the object method

 

This does not seem to be very simple, you can make a package of reflection related methods.

using DB.Interface;
using System;
using System.Reflection;
using System.Configuration;

namespace MyReflection
{
    /// <summary>
    /// 定义一个工厂
    /// </summary>
    public class SimpleFactory
    {
        //static关键字表示'静态',它的作用是当程序第一次调用类的时候完成初始化,就执行一次,而且只会执行一次。
        private static string IDBHelperConfig = ConfigurationManager.AppSettings["IDBHelperConfig"];
        private static string DllName = IDBHelperConfig.Split(',')[0];
        private static string TypeName = IDBHelperConfig.Split(',')[1];


        public static IDBHelper CreateInstance()
        {
            Assembly assembly = Assembly.Load(DllName);//程序集的名称
            Type type = assembly.GetType(TypeName);//获取类型
            object oDBHelper = Activator.CreateInstance(type);//创建对象
            IDBHelper iDBHelper = oDBHelper as IDBHelper;
            return iDBHelper;
        }
    }
}

You need to make a configuration in the App.config file:

 <appSettings>
    <add key="IDBHelperConfig" value="DB.MySql,DB.MySql.MySqlHelper"/>
  </appSettings>

 The reason for this is to facilitate the modification of the referenced assembly name.

The calling place can be written like this:

IDBHelper dBHelper = SimpleFactory.CreateInstance();
dBHelper.Query();

The execution result is still:

 

to sum up: 

The significance of reflection is that it can dynamically load the assembly to achieve the expansion of the program.

 

The above content is my personal understanding, there may be some errors or incompleteness.

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/112059074