这个问题来自论坛提问。
反射无非这么几步,获取Assembly,获取Type,获取MethodInfo,如果不是static方法则CreateInstance,最后Invoke就可以了。反射APP_CODE下面的类,无非是如何获取Assembly的问题,可以用"__code"或者"app_code"这两个AssemblyName获取。演示代码如下
aspx.cs
using System; using System.Reflection; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { System.Reflection.Assembly asm = Assembly.Load("__code"); //or:// System.Reflection.Assembly asm = Assembly.Load("app_code"); Type tp = asm.GetType("Tools"); if (tp != null) { object o = Activator.CreateInstance(tp);//创建实例 MethodInfo mi = tp.GetMethod("Reg");//反射方法 object ret = mi.Invoke(o, null);//执行方法 string str = ret.ToString();//获取结果 } } }
app_code/Tools.cs
using System; /// <summary> /// Test 的摘要说明 /// </summary> public class Tools { public string Reg() { return "aa"; } }