C# 如何从 if 语句中的布尔值中跳出 if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17727655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:19:42  来源:igfitidea点击:

How to break out of an if statement from a boolean inside the if statement

c#.netif-statement

提问by Chris

I have something like this

我有这样的事情

bool a = true;
bool b = true;
bool plot = true;
if(plot)
{
    if(a)
    {
        if(b)
            b = false;
        else
            b = true;
    //do some meaningful stuff here
    }
//some more stuff here that needs to be executed
}

I want to break out of the if statement that tests a when b turns false. Kind of like break and continue in loops. Any ideas? Edit: sorry forgot to include the big if statement. I want to break out of if(a) when b is false but not break out of if(plot).

我想在 b 变为 false 时跳出测试 a 的 if 语句。有点像 break 和 continue 循环。有任何想法吗?编辑:抱歉忘记包含大 if 语句。我想在 b 为假时跳出 if(a) 但不跳出 if(plot)。

采纳答案by Denise Skidmore

if(plot)
{
    if(a)
    {
        b= !b;
        if( b )
        {
            //do something meaningful stuff here
        }
    }
    //some more stuff here that needs to be executed
}

回答by dotixx

bool a = true;
bool b = true;
bool plot = true;
if(plot && a)
{
  if (b)
    b = false
  else
    b = true;

  if (b)
  {
    //some more stuff here that needs to be executed
  }
}

This should do what you want ..

这应该做你想做的..

回答by Sergey Berezovskiy

You can extract your logic into separate method. This will allow you to have maximum one level of ifs:

您可以将逻辑提取到单独的方法中。这将允许您最多拥有一级 if:

private void Foo()
{
   bool a = true;
   bool b = true;
   bool plot = true;

   if (!plot)
      return;

   if (a)
   {
      b = !b;
      //do something meaningful stuff here
   }

   //some more stuff here that needs to be executed   
}