C# 我是否应该从窗体关闭时的事件中注销?
我有以下代码:C# 我是否应该从窗体关闭时的事件中注销?,c#,events,C#,Events,我有以下代码: private void someButton_Click(object sender, EventArgs e) { SomeForm f = new SomeForm(); this.SomeEvt += f.someFunc; this.AnotherEvt += f.anotherFunc; f.Show(); } 我是否应该从this.SomeEvt注销f.someFunc,从this.AnotherEvt注销f.anotherFunc
private void someButton_Click(object sender, EventArgs e)
{
SomeForm f = new SomeForm();
this.SomeEvt += f.someFunc;
this.AnotherEvt += f.anotherFunc;
f.Show();
}
我是否应该从this.SomeEvt
注销f.someFunc
,从this.AnotherEvt
注销f.anotherFunc
当关闭f
时,我既不想执行f.anotherFunc
也不想执行someFunc
如果我应该取消注册,那么我该怎么做呢,因为在这个函数结束后不再有某种形式的f
我正在使用.Net framework 4.0和WinForms。根据您对我评论的回答: …当关闭
f
时,我不想执行f.anotherFunc
您应该注销事件,例如使用lambda:
private void someButton_Click(object sender, EventArgs e)
{
SomeForm f = new SomeForm();
this.SomeEvt += f.someFunc;
this.AnotherEvt += f.anotherFunc;
f.FormClosed += (ss, ee) => {
this.SomeEvt -= f.someFunc;
this.AnotherEvt -= f.anotherFunc;
};
f.Show();
}
另请阅读:这取决于当
AnotherEvt
事件被触发,但f
已关闭时(即当f
关闭时,您是否希望执行f.anotherFunc
)@DmitryBychenko,否,我不想在关闭f
时执行f.anotherFunc
,然后将f.CloseForm+=OnMyFormClose
相加,并在取消注册事件的位置实现OnMyFormClosed
:;this.AnotherEvt-=f.anotherFunc@DmitryBychenko,谢谢你我从来没有意识到注册一个事件来注销另一个事件的讽刺之处,在看到它写在lambda中之前…@Marwie:非常基本的termine回调函数中有一个讽刺之处,因为这个没有传递给f.Show()
,使用someButton\u点击事件关闭表单后,SomeForm
是否有被关闭的风险?在这种情况下,从SomeForm
返回到this
表单的引用不会导致垃圾收集器无法收集this
表单吗?@Martin Brown:你说得很对,如果MainForm
(让namethis
像那样)关闭了SomeForm
(f
)已经关闭了。我不认为这一延误是至关重要的;如果是,可以再添加一个lambda:this.FormClosed+=(ss,ee)=>f.Close()代码>