C#反射

1.什么是反射(Reflection)
System.Reflection 命名空间中的类与 System.Type 使你能够获取有关加载的程序集和其中定义的类型的信息,如类、接口和值类型。

2.反射能干什么
可以使用反射在【运行时】创建、调用和访问类型实例。说白了就是通过反射能够获取一个未知类的类型。

3.通过代码解读反射

  • System.Type获取有关加载的程序集和其中定义的类型的信息
public class ReflectionTest {
        
        /// <summary>
        /// 反射名称
        /// </summary>
        public string ReflectionName { get; set; }

        public string GetName()
        {
            return "张三";
        }
}
Type type = typeof(ReflectionTest);
string name = type.Name;//获取当前成员的名称
string fullName = type.FullName;//获取类的全部名称不包括程序集
string nameSpace = type.Namespace;//获取该类的命名空间
var assembly = type.Assembly;//获取该类的程序集名
var module = type.Module;//获取该类型的模块名            
var memberInfos = type.GetMembers();//得到所有公共成员
  • 反射构造带参的例子(带参)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace FanShe3
{
    class Test
    {
        public Test(string Say)
        {
            Console.WriteLine(Say);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Test t;
            string Say = "哈哈!!创建成功";
            //开始创建反射,这个是获取当前程序集的意思,如果需要反射类库可以使用Assembly.Load的方法
            Assembly asm = Assembly.GetExecutingAssembly();
            //需要注意的地方是,如果反射的构造函数带参只是一个,这里创建的也必须是一个参数的Object数组,而且顺序也必须和构造函数一样
            object[] Obj = new object[1];
            Obj[0] = Say;
            t = (Test)asm.CreateInstance("FanShe3.Test", true, BindingFlags.Default, null, Obj, null, null);

            Console.ReadKey();
        }
    }
}
  • 传递对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace FanShe4
{
    class Test
    {
        public Test(Test2 t2)
        {
            t2.Say();
        }
    }

    public class Test2
    {
        public void Say()
        {
            Console.WriteLine("哈哈!!创建成功");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test t;
            Test2 t2 = new Test2();
            //开始创建反射,这个是获取当前程序集的意思,如果需要反射类库可以使用Assembly.Load的方法
            Assembly asm = Assembly.GetExecutingAssembly();
            //需要注意的地方是,如果反射的构造函数带参只是一个,这里创建的也必须是一个参数的Object数组,而且顺序也必须和构造函数一样
            object[] Obj = new object[1];    
            Obj[0] = t2;
            t = (Test)asm.CreateInstance("FanShe4.Test", true, BindingFlags.Default, null, Obj, null, null);

            Console.ReadKey();
        }
    }


}
原文地址:https://www.cnblogs.com/ButterflyEffect/p/10265941.html