Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我是否应该从窗体关闭时的事件中注销?_C#_Events - Fatal编程技术网

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
(让name
this
像那样)关闭了
SomeForm
f
)已经关闭了。我不认为这一延误是至关重要的;如果是,可以再添加一个lambda:
this.FormClosed+=(ss,ee)=>f.Close()