如果子方法在 C# 中被 return 停止,则主方法 returns

Main method returns if submethod has stopped by return in C#

假设我有两个事件处理程序:

private void button1_click(object sender, EventArgs e)
{
   //Do first stuffs

   button2_click(sender, e);

   //Do second stuffs
}

private void button2_click(object sender, EventArgs e)
{
   //Do something

   if(myCondition) return; //Also return in button1_click

   //Do something else
}

如果 button2_click 因 return 停止,是否有任何方法可以在 button1_click 中 return 并跳过 //Do second stuffs 部分?

我正在寻找一种方法,而不是使用 public bool 变量来检查 button2_click 中的 myCondition 是否为 true

我想,你想要这样的东西

private void button1_click(object sender, EventArgs e)
{
    //Do first stuffs

    button2_click(sender, e);

    //Reading the tag value of sender object that is assigned in that case
    if (!(bool)(sender as Button).Tag)
        return;
    //Do second stuffs
}

private void button2_click(object sender, EventArgs e)
{
    //Do something
    //Since sender object is button1 in the example
    Button button = sender as Button;

    button.Tag = true;

    if (myCondition)
    {
        button.Tag = false;
        return;
    }//Also return in button1_click

    //Do somthing else
}

我的建议是将每个处理程序的有意义的部分提取到可以独立调用并且可以具有有用的 return 值的方法中。这对于您的第二个按钮的处理程序特别重要,因为 button1 的处理程序也依赖于它。

提取代码后,您可以将提取的方法转换为布尔函数,并可以根据 return 值继续您的过程。

private void button1_click(object sender, EventArgs e)
{
   ThingToDoForButton1();
}

private void button2_click(object sender, EventArgs e)
{
   ThingToDoForButton2();
}

private void ThingToDoForButton1()
{
    // do something 

    if (ThingToDoForButton2())
    {
         // do something else
    }
}

private bool ThingToDoForButton2()
{
    //Do something

    if(/* some condition */) return false; 

    //Do something else

    return true;
}

当然,如果 "do something" 和 "do something else" 部分是不是微不足道的。

您可以这样使用 CancelEventArgs Class

private void button1_click(object sender, EventArgs e)
{
    //Do first stuffs
    var e1 = new CancelEventArgs();
    button2_click(sender, e1);
    if(e1.Cancel) 
    {
       return;
    }
   //Do second stuffs
}

private void button2_click(object sender, CancelEventArgs e)
{
   //Do somthing

   if(myCondition)
   {
      e.Cancel = true;
      return; 
   }

   //Do somthing else
}