反射是一个程序集发现及运行的过程,通过反射可以得到 .exe和 .dll 等程序集内部信息,使用反射可以看到程序集内部类,方法,接口,结构,属性,特性等信息。
命名空间类System.Reflection内包含多个反射常用类。
举个栗子:
Assembly 通过此类可以加载操纵一个程序集,并获取程序集内部信息
EventInfo 该类保存给定事件信息
FieldInfo 该类保存给定字段信息
MethodInfo 该类保存给定方法信息
MemberInfo该类是一个基类,它定义了EventInfo、FieldInfo、MethodInfo、PropertyInfo的多个公用行为
Module 该类可以使你能访问多个程序集中的给定模块
ParameterInfo 该类保存给定的参数信息
PropertyInfo 该类保存给定的属性信息
System.Reflection.Assembly类
通过Assembly类可以动态加载程序集,并查看程序集内部信息,常用Load();
举个栗子:
Assembly assembly = Assembly.Load("AssemblyTest");
利用Assembly的object CreateInstance(string) 方法可以反射创建一个对象,参数0为类名。
System.Type
Type是最常用的类,可以通过Type得到一个类的内部信息,也可以通过反射创建一个对象
Type t = typeof(Example);// 利用typeof();
//利用System.Object.GetType() 得到Type对象
Example example=new Example();
Type type=example.GetType();
// 利用System.Type.GetType() 得到Type对象
//参数一:程序集限量名称
//参数二:true 则引发异常(如果找不到类型);false 则返回null.Specifyingfalse
//参数三:执行的搜索不区分大小写则为 true,为 typeName 执行的搜索区分大小写则为 false。
Type type=Type.GetType("MyAssembly.Example",false,true);
//最常见的是利用反射与Activator结合来创建对象。
Assembly assembly= Assembly.Load("MyAssembly");
Type type=assembly.GetType("Example");
object obj=Activator.CreateInstance(type);
反射方法
通过System.Reflection.MethodInfo查找类的方法:
Type type=typeof(Example);
MethodInfo[] listMethodInfo=type.GetMethods(); //获取方法集
foreach(MethodInfo methodInfo in listMethodInfo)
Cosole.WriteLine("Method name is "+methodInfo.Name); //循环方法名
使用反射方法执行类里的方法:
Assembly assembly= Assembly.Load("MyAssembly");
Type type=assembly.GetType("Example");
object obj=Activator.CreateInstance(type);
MethodInfo methodInfo=type.GetMethod("Hello World"); //根据方法名获取MethodInfo对象
methodInfo.Invoke(obj,null); //参数1类型为object[],代表Hello World方法的对应参数,输入值为null代表没有参数
反射属性
通过System.Reflection.PropertyInfo查找类的属性
Type type=typeof(Example);
PropertyInfo[] listPropertyInfo=type.GetProperties(); //获取属性集
foreach(PropertyInfo propertyInfo in listPropertyInfo)
Cosole.WriteLine("Property name is "+ propertyInfo.Name); //循环属性集
反射字段
通过System.Reflection.FieldInfo查找到类里面的字段
SetValue(object ,object )和GetValue(object) 因为使用方法与反射属性非常相似
ActivatorTest activatorTest = new ActivatorTest();
System.Reflection.FieldInfo fieldInfo = activatorTest.GetType().GetField("nn");
Console.WriteLine(fieldInfo.Name+":"+ fieldInfo.GetValue(activatorTest));
fieldInfo.SetValue(activatorTest, "123");
Console.WriteLine(fieldInfo.GetValue(activatorTest));
反射特性
通过System.Reflection.MemberInfo的GetCustomAttributes(Type,bool)就可反射出一个类里面的特性,以下例子可以反射出一个类的所有特性
Type type=typeof("Example");
object[] typeAttributes=type.GetCustomAttributes(false); //获取Example类的特性
foreach(object attribute in typeAttributes)
Console.WriteLine("Attributes description is "+attribute.ToString());