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

UserControl (ASCX) 向頁面 (ASPX) 傳值:以 Reflection InvokeMember 實作

     編輯:ASP.NET 基礎

UserControl 需將兩個 TextBox 的值傳回母頁面的 Label 顯示。傳統做法有公開屬性、事件、介面、FindControl 等;本文示範另類做法:在 UserControl 按鈕事件中,透過 this.Page.GetType().InvokeMember 呼叫母頁面的 public void ReadUCMessage(string, string) 方法。

母頁面

public partial class _Default : Page {
    public void ReadUCMessage(string v1, string v2) {
        LabelshowFirstValue.Text = v1;
        LabelshowLastValue.Text = v2;
    }
}

UserControl 程式碼

public partial class InsusUC : UserControl {
    protected void ButtonTransmit_Click(object sender, EventArgs e) {
        string v1 = TextboxFirstName.Text.Trim();
        string v2 = TextboxLastName.Text.Trim();
        this.Page.GetType().InvokeMember("ReadUCMessage",
            BindingFlags.InvokeMethod, null, this.Page, new object[] { v1, v2 });
    }
}

關鍵點解析

  • InvokeMember 參數:方法名、BindingFlags.InvokeMethod、binder(null)、目標物件(this.Page)、引數陣列
  • 母頁面方法必須為 public 且簽章完全相符
  • 若方法不存在或參數不符會拋 MissingMethodException / TargetParameterCountException

優缺點評析

優點缺點
無需在 UserControl 定義事件/介面編譯期無法檢查方法是否存在,易拼錯字串
母頁面不需繼承特定基類效能較直接呼叫慢(反射開銷)
鬆散耦合,UserControl 可重用於任何含同名方法的頁面除錯困難,堆疊追蹤不明確

建議

教學/原型可用;正式專案優先用 介面 或 事件,保障型別安全與可維護性。若確需反射,請將方法名常數化並加上單元測試驗證簽章相容。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved