天天看點

反射使用的簡單執行個體

//建立一個程式集執行個體

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[]{"歡迎!"}));

繼續閱讀