反射使用的简单实例

//创建一个程序集实例

System.Reflection.Assembly  a= System.Reflection.Assembly.LoadFrom(Server.MapPath("../Public/bin/Debug/Public.dll"));

 

//定义一个类型数组并从程序集实例中获得

Type[] t = a.GetTypes();

             

//循环输出类型数组中的类的名称       

for(int i = 0 ; i<t.Length;i++)

{

      Response.Write(t[i].Name+"<br>");

}

 

 

//定义一个方法信息实例 并从程序集中指定名称的类中指定名称的方法获得

System.Reflection.MethodInfo m = a.GetType("Public.Jscript").GetMethod("Alert");

             

//同上,只不过是通过索引获得 t是a.GetTypes数组

//System.Reflection.MethodInfo m = t[3].GetMethod("Alert");

 

//调用方法信息实例的Invoke方法,并传递参数,来执行反射做要指定指定的类的方法,其中参数1是类创建的实例,参数2是所要执行的方法的参数的对象数组    *说明:System.Activator.CreateInstance是动态创建指定类实例的方法

Response.Write(m.Invoke(System.Activator.CreateInstance(a.GetType("Public.Jscript")),new object[]{"欢迎!"}));

 
posted @ 2007-08-23 15:45  ZetaChow晓代码  阅读(142)  评论(0编辑  收藏  举报