反射
1. 程序集里的元数据
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\x64\ildasm.exe
用这个工具打开一个assembly。
file -> dump -> dump metainfo, 保存到dump.txt中, 看这个文件。
编译生成il代码,和类的metainfo。
AppDomain
一个程序运行起来以后,有一个AppDomain,在这个AppDomain中放了我们用到的所有assembly。
需要using System.Reflection;
Assembly的组成
2. 反射
反射概念:
在程序运行时,动态获取 程序集, 类型(class,interface)和类型的成员信息(方法,字段,属性等)。
在程序运行时,动态创建 类型实例, 以及调用和方法 动态创建出来的 类型实例的成员。
反射的应用:框架(Spring .net/ .Net MVC等)
在程序运行时,动态获取 程序集:
class Program
{
static void Main(string[] args)
{
Assembly[] ass = AppDomain.CurrentDomain.GetAssemblies();
Person p = new Person();
p.TestAssembly();
}
}
class Person {
public String Name { get; set; }
public int Age { get; set; }
private int id;
public void TestAssembly() {
Assembly ass = this.GetType().Assembly;
Type[] types = ass.GetTypes();
Type currentType = ass.GetType();
//根据类的full name,获取在内存中的类型对象
Type typeByFullName = ass.GetType("ConsoleApplication6.Person");
Type type = this.GetType();
MethodInfo[] methods = this.GetType().GetMethods();
this.GetType().GetMembers();
this.GetType().GetMember("Name");
FieldInfo field = type.GetField("id");
PropertyInfo prop = type.GetProperty("Name");
}
}
在程序运行时,动态创建 类型实例:在Person类中加下面4个方法,在Main中测试
public void CreatePersonObject() {
Type type = this.GetType();
//使用Person类的Type对象,创建一个Person对象
Person p = Activator.CreateInstance(type) as Person;
Person p1 = Activator.CreateInstance<Person>();
//使用Person类的Name属性对象,为p的Name属性赋值
PropertyInfo prop = type.GetProperty("Name");
prop.SetValue(p1, "toto");
Console.WriteLine(p1.Name);
//使用Person类的Sayhi方法对象,调用p1的Sayhi方法
MethodInfo method = type.GetMethod("Sayhi");
method.Invoke(p1, null);
MethodInfo method1 = type.GetMethod("ShowNumber");
object[] arrParams = {2};
method1.Invoke(p1, arrParams);
MethodInfo method2 = type.GetMethod(&#