反射

假设现在有一个Dog类,有三个字段,一个方法,通过反射来操作字段和方法

类如下:

namespace C03反射
{
    public class Dog
    {
        public string name;
        public int age;
        private bool gender;

        public string ShoutHi()
        {
            return this.name + "," + this.age + " , " + this.gender;
        }
    }
}

反射调用:

    private void btnAssemblyTest_Click(object sender, EventArgs e)
        {
            //***********************普通 方式 创建 和 调用***********************
            Dog d = new Dog();
            d.name = "123";
            d.ShoutHi();

            //***********************反射 获取 类的成员***********************
            //1.获取当前正在运行的  程序集(Assembly)对象
            //或者可以加载外部DLL  
//Assembly myAssembly = Assembly.LoadFrom("d:debugDog.dll");
            //Type svcTypes = myAssembly.GetType("C03反射.Dog");//类名,程序集名称

Assembly ass = this.GetType().Assembly;//获取当前运行对象所属的类所在的程序集对象 //2.获取 程序集中的 Dog类的 类型(Type)对象 Type tDog = ass.GetType("C03反射.Dog"); //3.获取 Dog 类的 name 字段对象 FieldInfo fInfo = tDog.GetField("name"); //4.获取 Dog 类的 ShoutHi 方法对象 MethodInfo mInfo = tDog.GetMethod("ShoutHi"); //***********************反射 调用 类的成员*********************** //1.根据 Dog的Type对象,实例化一个Dog对象 Dog d2 = Activator.CreateInstance(tDog) as Dog; //Dog d3 = Activator.CreateInstance<Dog>(); //2.使用 Dog类的 name字段对象,为 d2实例 的 name字段赋值 //相当于:d2.name="小白" fInfo.SetValue(d2, "小白"); //3.使用 Dog类的 ShoutHi方法对象,调用 d2实例的 ShoutHi方法 // 其实就是执行方法体代码,并将d2设置为方法里的this //相当于:d2.ShoutHi(); string strRes = mInfo.Invoke(d2, null).ToString(); MessageBox.Show(strRes); }

 获取类型的方法:

    private void btnGetType01_Click(object sender, EventArgs e)
        {
            Assembly ass = this.GetType().Assembly;
            //通过程序集获取 Type
            //1.通过 类的全名称 获取 类的类型对象
            Type t = ass.GetType("C03反射.Dog");
            //2.通过 程序集 获取所有的 公共的(puclic) 类型
            Type[] types = ass.GetExportedTypes();
            //3.通过 程序集 获取所有的类型
            Type[] typesAll = ass.GetTypes();

            //获取单个 类型对象
            //1.通过类 直接过去 类型对象
            Type t2 = typeof(Dog);
            //2.通过对象 来获取 类型对象
            Type t3 = this.GetType();

            Dog d3 = new Dog();
            Type t4 = d3.GetType();


        }
原文地址:https://www.cnblogs.com/happygx/p/3390230.html