【问题标题】:How to exit "braced scope"?如何退出“支撑范围”?
【发布时间】:2020-02-19 19:41:10
【问题描述】:

是否可以在 C# 中退出作用域,例如可以将 break 退出循环?

private void a()
{
    // do stuff here

    {
        // do more stuff here

        break;? //<-- jump out of this scope here!! break won't work

        // this further code should not be executed
    }

    // do stuff here
}

【问题讨论】:

  • do 放在{ 之前和while(false) 之后放在} 之后,break 将起作用...
  • 使用return;关键字
  • 您可以使用break 跳出循环或切换。
  • @Alberto 永远不会允许执行最后一个 // do stuff here
  • @Fildor 这只是“代码组织”。我不想创建一个新方法(你可以使用return;,所以我做了一个范围。现在我最终创建了一个新方法。

标签: c# break


【解决方案1】:

您可以使用break 跳出循环或切换,但不能跳出这样的简单块。

有一些方法可以实现这一点,例如使用goto 或人工while 循环,但这听起来绝对像是代码异味。

您可以使用简单的条件实现您想要的,这将使您的意图更加清晰。

代替:

DoSomething();
if (a == 1) // conditional break
{
    break;
}
DoSomethingElse();
break; // unconditional break (why though)
UnreachableCode(); // will generate compiler warning, by the way

你可以这样做:

DoSomething();
if (a != 1) // simple condition
{
    DoSomethingElse();
    if (false) // why though
    {
        UnreachableCode(); // will generate compiler warning, by the way
    }
}

或者,您可以使用return 语句将此部分提取到单独的命名方法和短路。有时,它确实使代码更具可读性,尤其是当您有返回值时:

private void a()
{
    // do stuff here

    MeaningfulNameToDescribeWhatYouDo();

    // do stuff here
}

private void MeaningfulNameToDescribeWhatYouDo()
{
    // do more stuff here

    if (condition)
    {
        return; //<-- jump out of this scope here!!
    }

    // this further code should not be executed
}     

【讨论】:

    【解决方案2】:

    是的,可以使用goto 语句,但我强烈建议您在获得更多语言经验之前不要使用它们。我从不使用 goto,也不知道有哪个程序员这样做,因为它会使你的代码变得像意大利面条一样混乱,而且通常有更好的选择。

    有办法负责任地使用它们,但从您的问题来看,您似乎不确定如何正确使用 if/else/while 等语句。相反,最好使用适当的流量控制。

    https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto

    【讨论】:

      猜你喜欢
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 2020-04-12
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多