這個問題來自論壇提問。
反射無非這麼幾步,獲取Assembly,獲取Type,獲取MethodInfo,如果不是static方法則CreateInstance,最後Invoke就可以了。反射APP_CODE下面的類,無非是如何獲取Assembly的問題,可以用"__code"或者"app_code"這兩個AssemblyName獲取。演示代碼如下
ASPx.cs
01.using System;
02.using System.Reflection;
03.public partial class _Default : System.Web.UI.Page
04.{
05. protected void Page_Load(object sender, EventArgs e)
06. {
07. System.Reflection.Assembly asm = Assembly.Load("__code");
08. //or:// System.Reflection.Assembly asm = Assembly.Load("app_code");
09. Type tp = asm.GetType("Tools");
10. if (tp != null)
11. {
12. object o = Activator.CreateInstance(tp);//創建實例
13. MethodInfo mi = tp.GetMethod("Reg");//反射方法
14. object ret = mi.Invoke(o, null);//執行方法
15. string str = ret.ToString();//獲取結果
16. }
17. }
18.}
app_code\Tools.cs
01.using System;
02./// <summary>
03./// Test 的摘要說明
04./// </summary>
05.public class Tools
06.{
07. public string Reg()
08. {
09. return "aa";
10. }
11.}