反射

1.在一个WINFORM中建立一个类

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

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

使用的时候在主程序

  //1.获取当前正在运行的  程序集(Assembly)对象
      Assembly ass = this.GetType().Assembly;//获取当前运行对象所属的类所在的程序集对象
  //2.获取 程序集中的 Dog类的 类型(Type)对象
       Type tDog = ass.GetType("C03反射.Dog");
       Type[] tDogs = ass.GetTypes();//获取所有的类型
 //3.通过 程序集 获取所有的 公共的(puclic) 类型
      Type[] types = ass.GetExportedTypes();

image

注意这里并不是拿一个实例。

//拿到所有的字段
 FieldInfo[] fInfos = tDog.GetFields();

image

//3.获取 Dog 类的 name 字段对象
    FieldInfo fInfo = tDog.GetField("name");

image

 MethodInfo[] mInfos = tDog.GetMethods();//获取所有的方法



image

注意这里他不仅获取到了我们自己定义的方法,还把从基类OBJECT继承下来的方法也显示出来

同理image

这样可以获取一个方法

 //1.根据 Dog的Type对象,实例化一个Dog对象
     Dog d2 = Activator.CreateInstance(tDog) as Dog;
     Dog d3 = Activator.CreateInstance<Dog>();

image

注意:Activator.CreateInstance(tDog)这样是一个Object类型,需要转换下。第二个方法是硬编码,把类型写死了,用的相对少一点。

 
 
image
 

image

FieldInfo fInfo = tDog.GetField("name");
fInfo.SetValue(d2, "小白");
这样是为一个字段赋值,赋值前后名字发生了改变。
 
 MethodInfo mInfo = tDog.GetMethod("ShoutHi");
 Dog d2 = Activator.CreateInstance(tDog) as Dog;
 string strRes = mInfo.Invoke(d2, null).ToString();
  MessageBox.Show(strRes);

image

反射方式调用方法

根据路径加载程序集

string strPath = @"M:黑马四期2013-04-22 泛型反射CodeC01泛型libsC01泛型.exe";
Assembly ass = Assembly.LoadFrom(strPath);
原文地址:https://www.cnblogs.com/automation/p/3416390.html