首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

ASP.NET 透過反射存取 App_Code 目錄下的類別與方法

     編輯:關於C語言

問題背景

ASP.NET 動態編譯的 App_Code 目錄下類別不在主組件中,需透過特定組件名稱載入。

反射步驟範例

// ASPx.cs
using System;
using System.Reflection;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Assembly asm = Assembly.Load("__code"); // 或 "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;
public class Tools
{
    public string Reg()
    {
        return "aa";
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved