在 Windows Forms 應用程式中,子表單(AddForm)需呼叫父表單(RedoForm)的公用方法 load() 重新載入資料。常見做法是透過屬性暴露父表單參考:
public RedoForm pForm { get; set; }
但在呼叫 this.pForm.load() 時拋出 NullReferenceException,原因在於 pForm 尚未被指派實例。
this 傳入:var child = new AddForm(...);
child.pForm = this; // 關鍵步驟
child.Show();
public AddForm(RedoForm parent) {
InitializeComponent();
this.pForm = parent;
}
更鬆耦合的做法是讓子表單定義事件,父表單訂閱:
// 子表單
public event Action RefreshRequested;
private void OnRefresh() => RefreshRequested?.Invoke();
// 父表單
child.RefreshRequested += () => this.LoadData();
此模式避免子表單直接依賴父表單具體型別,符合「依賴倒置原則」,且天然解決空參考問題。