一:反射的定义
审查元数据并收集关于它的类型信息的能力。元数据(编译以后的最基本数据单元)就是一大堆的表,当编译程序集或者模块时,编译器会创建一个类定义表,一个字段定义表,和一个方法定义表等。
System.reflection命名空间包含的几个类,允许你反射(解析)这些元数据表的代码
System.Reflection.Assembly
System.Reflection.MemberInfo
System.Reflection.EventInfo
System.Reflection.FieldInfo
System.Reflection.MethodBase
System.Reflection.ConstructorInfo
System.Reflection.MethodInfo
System.Reflection.PropertyInfo
System.Type
二:获取类型信息:
class MyClass
{
public string m;
public void test() { }
public int MyProperty { get; set; }
}
//获取类型信息
protected void Button1_Click(object sender, EventArgs e)
{
Type type = typeof(MyClass);
Response.Write("类型名:" + type.Name);
Response.Write("<br/>");
Response.Write("类全名:" + type.FullName);
Response.Write("<br/>");
Response.Write("命名空间名:" + type.Namespace);
Response.Write("<br/>");
Response.Write("程序集名:" + type.Assembly);
Response.Write("<br/>");
Response.Write("模块名:" + type.Module);
Response.Write("<br/>");
Response.Write("基类名:" + type.BaseType);
Response.Write("<br/>");
Response.Write("是否类:" + type.IsClass);
Response.Write("<br/>");
Response.Write("类的公共成员:");
Response.Write("<br/>");
MemberInfo[] memberInfos = type.GetMembers();//得到所有公共成员
foreach (var item in memberInfos)
{
Response.Write(string.Format("{0}:{1}", item.MemberType, item));
Response.Write("<br/>");
}
}
三:获取程序集信息
protected void Button2_Click(object sender, EventArgs e)
{ //获取当前执行代码的程序集
Assembly assem = Assembly.GetExecutingAssembly();
Response.Write("程序集全名:"+assem.FullName);
Response.Write("<br/>");
Response.Write("程序集的版本:"+assem.GetName().Version);
Response.Write("<br/>");
Response.Write("程序集初始位置:"+assem.CodeBase);
Response.Write("<br/>");
Response.Write("程序集位置:"+assem.Location);
Response.Write("<br/>");
Response.Write("程序集入口:"+assem.EntryPoint);
Response.Write("<br/>");
Type[] types = assem.GetTypes();
Response.Write("程序集下包含的类型:");
foreach (var item in types)
{
Response.Write("<br/>");
Response.Write("类:"+item.Name);
}
}
四:反射调用方法
protected void Page_Load(object sender, EventArgs e) { System.Reflection.Assembly ass = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory+"bin\\WebApplication1.dll"); //加载DLL System.Type t = ass.GetType("WebApplication1.MainPage");//获得类型 string name=typeof(MainPage).AssemblyQualifiedName; System.Type t1 = Type.GetType(name); System.Type t2 = typeof(MainPage); object o = System.Activator.CreateInstance(t);//创建实例 System.Reflection.MethodInfo mi = t.GetMethod("RunJs1");//获得方法 mi.Invoke(o, new object[] { this.Page, "alert('测试反射机制')" });//调用方法 System.Reflection.MethodInfo mi1 = t.GetMethod("RunJs"); mi1.Invoke(t, new object[] { this.Page, "alert('测试反射机制1')" });//调用方法 }