如何退出"braced scope"?
How to exit "braced scope"?
是否可以在 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
}
您可以使用 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
语句进行短路。有时,它确实使代码更具可读性,尤其是当您有 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
}
是的,可以使用 goto
语句,但我强烈建议您在获得更多语言经验之前不要使用它们。我从不使用 goto,而且我不知道有哪个程序员会这样做,因为它会使您的代码变得一团糟,而且通常有更好的选择。
有一些方法可以负责任地使用它们,但从您的问题来看,您似乎不确定如何正确使用 if/else/while 等语句。相反,最好使用适当的流量控制。
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
是否可以在 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
}
您可以使用 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
语句进行短路。有时,它确实使代码更具可读性,尤其是当您有 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
}
是的,可以使用 goto
语句,但我强烈建议您在获得更多语言经验之前不要使用它们。我从不使用 goto,而且我不知道有哪个程序员会这样做,因为它会使您的代码变得一团糟,而且通常有更好的选择。
有一些方法可以负责任地使用它们,但从您的问题来看,您似乎不确定如何正确使用 if/else/while 等语句。相反,最好使用适当的流量控制。
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto