[英]Generic method to register/unregister event handler
我試圖找出一種使事件注冊和注銷與我的初始化和清除保持同步的方法。 我想要的是能夠調用通用方法來注冊或注銷事件,並且僅傳遞布爾值來進行操作。
我不想與Window一起使用,但這只是一個簡單的示例。
class EventSample
{
private Window myWindow;
public EventSample(Window window)
{
myWindow = window;
InitEvent(true);
}
~EventSample()
{
InitEvent(false);
}
private void InitEvent(bool register)
{
// I want a generic similar to that
RegisterEvent(register, myWindow.Activated, MyWindow_Activated);
RegisterEvent(register,myWindow.Closed , MyWindow_Closed);
RegisterEvent(register, myWindow.Closing ,MyWindow_Closing);
}
private void MyWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void MyWindow_Closed(object sender, EventArgs e)
{
}
private void MyWindow_Activated(object sender, EventArgs e)
{
}
}
我在清理方法上也遇到過類似的問題。 我已經解決了這一問題,方法是保留處理窗口或控件時要執行的動作的列表。
像這樣:
this.RegisterEvent
( () => this.Event += handler
, () => this.Event -= handler
);
RegisterEvent
執行(在我的情況下為延遲)事件附件:
private List<Action> unregisterEvents = new List<Action>();
private void RegisterEvent(Action registerAction, Action unregisterAction)
{
registerAction.Invoke();
unregisterEvents.Add(unregisterAction);
}
處理時,只需遍歷注銷事件即可:
foreach (Action a in unregisterEvents)
{
a.Invoke();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.