条件委托

本文关键字:条件 | 更新日期: 2023-09-27 17:56:26

用户完成表单"f"后,表单将保留一个值,我想在运行doStuff()之前检查该值。 比如,如果 f.value> 0 ,则运行 doStuff(),否则,不要运行 doStuff()。 如何最简洁地修改代码以允许此检查? 我不太明白何时分配委托,如果我传递 f.value,它会在我添加委托时还是在运行委托时获取值?

form f = new form();
f.Show();
f.FormClosing += delegate{doStuff();};

谢谢!

条件委托

您可以在进行委托时捕获引用的值:

f.FormClosing += delegate { if(f.value > 0) doStuff(); };

事件发生时,它将检查捕获的引用f的当前值,如果条件匹配,则继续执行。

form f = new form();
f.Show();
f.FormClosing += delegate{if(f.Value>0){doStuff();}};

我相信它在运行时使用该值,而不是在分配时使用该值。因此,当 FormClosing 事件触发时,它将使用 f.Value 的值

像这样吗?

        form f = new Form();
        f.Show();
        f.FormClosing += (s, a) =>
                             {
                                 if (f.Value > 0)
                                 {
                                     doStuff();
                                 }
                             };

我的理解是 lambda 是在它们定义的范围内运行的,所以......

form f = new form();
f.Show();
f.FormClosing += delegate
{
   if(f.Value > 0)
      doStuff();
};

您可以使用常规语法来实现它

form f = new form();
f.FormClosing += FormClosingHandler; // Add unanonaymous delegate to the event handler
f.Show();
private void FormClosingHandler(object sender, FormClosingEventArgs e)
{
   var form = (form)sender;
   form.FormClosing -= FormClosingHandler; // Unsubscribe from the event to prevent memory leak
   if(form.value > 0)
   {
      doStuff();
   }
}

我不会这样做。我会让表单处理这一切。只需运行表单...

public void showMyForm()
{
    form f = new form();
    f.Show();
}

。然后在表单.cs文件中定义表单关闭事件,并在表单本身中链接该事件...

public partial class form : Form
{
    //Link the event in the IDE and let InitializeComponent() add it. Then perform the
    //the things you want in the form itself based on your condition
    private void doStuff(object sender, FormClosingEventArgs e) //Think that's the right args
    {
        if (this.value > 0)
        {
            //code you want to execute.
        }
    }
}

如果 f.Value 是表单的成员,它将在运行委托时进行检查,您将获得当时分配的值,而不是在您分配委托的那一刻。