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;
}
}
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 可重用於任何含同名方法的頁面 | 除錯困難,堆疊追蹤不明確 |
教學/原型可用;正式專案優先用 介面 或 事件,保障型別安全與可維護性。若確需反射,請將方法名常數化並加上單元測試驗證簽章相容。