简体   繁体   中英

Should I unregister from event on form closing?

I have following code:

private void someButton_Click(object sender, EventArgs e)
{
    SomeForm f = new SomeForm();
    this.SomeEvt += f.someFunc;
    this.AnotherEvt += f.anotherFunc;
    f.Show();
}

Should I unregister f.someFunc from this.SomeEvt and f.anotherFunc from this.AnotherEvt ?

I don't want to perform neither f.anotherFunc nor someFunc when f is closed

And if I should do unregister , then how would I do that because there no longer SomeForm f after ending of this function?

I'm using .Net framework 4.0 and WinForms.

According to your answer to my comment:

...I don't want to perform f.anotherFunc when f is closed

you should unregister the event, eg with 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM