何时在C#中使用'continue'关键字

Rio*_*ams 32 .net c# continue

最近,我正在经历一个开源项目,尽管我已经在.NET中开发了几年,但我之前并没有偶然发现这个continue关键字.

问题:使用continue关键字可以从中受益的最佳做法或领域是什么?有没有理由我以前可能没见过它?

Ant*_*ram 44

如果适用,您可以使用它立即退出当前循环迭代并开始下一个迭代.

foreach (var obj in list)
{
    continue;

    var temp = ...; // this code will never execute
}
Run Code Online (Sandbox Code Playgroud)

A continue通常与条件有关,通常可以用条件代替条件continue;

foreach (var obj in list)
{ 
    if (condition)
       continue;

    // code
} 
Run Code Online (Sandbox Code Playgroud)

可以写成

foreach (var obj in list)
{
    if (!condition)
    {
        // code
    }
}
Run Code Online (Sandbox Code Playgroud)

continue如果你可能if在循环中有几个级别的嵌套逻辑,那么会变得更有吸引力.一个continue代替嵌套可能使代码更易读.当然,将循环和条件重构为适当的方法也会使循环更具可读性.


Mik*_*sen 15

continue关键字用于跳过循环块的其余部分并继续.例如:

for(int i = 0; i < 5; i++)
{
   if(i == 3) continue; //Skip the rest of the block and continue the loop

   Console.WriteLine(i);
}
Run Code Online (Sandbox Code Playgroud)

将打印:

0
1
2
4
Run Code Online (Sandbox Code Playgroud)


Kon*_*ski 12

它可以防止深度嵌套.

foreach(var element in collection)
{
    doSomething();      
    doSomethingElse();
    if (condition1)
    {
        action1();
        action2();
        if (condition2)
        {
           action3();                            
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可以改写为

foreach(var element in collection)
{
    doSomething();      
    doSomethingElse();
    if (!condition1)
    {
       continue;
    }
    action1();
    action2();
    if (!condition2)
    {
       continue;
    }
    action3();
}
Run Code Online (Sandbox Code Playgroud)

如果代码块不是微不足道但是垂直地更大,则使用continue可以提高代码可读性.显然它应该像其他语言结构一样被考虑使用.

  • +1回答最佳实践部分.我真的很讨厌那些长篇if-blocks. (6认同)

Joe*_*Joe 11

当你不想break退出循环,但你想要下一次迭代:

for (int i = 0; i < something; i++)
{
    if (condition)
        continue;

    // expensive calculations, skip due to continue
    // or due to the condition above I don't want to 
    // run the following code
    stuff();
    code();
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 8

你应该谨慎使用它.

最好(=最容易阅读)的循环不使用break或者continue,它们是一种结构化的goto语句.

话虽如此,1或甚至2个break/continue语句不会使循环变得不可读,但是为了使它们清晰并保持简单而付出代价是值得的.

  • `goto`的问题在于它允许任意跳转到代码中的任何一点.`continue`重新启动最近的封闭循环.我认为对"goto"的批评不适用.如果他们这样做,他们也适用于`return`和`throw`. (5认同)

Yah*_*hia 7

基本上continue并且break是更好(但通常只是伪装)的goto陈述......

每当你进入一个循环并且知道循环中接下来的所有内容都应该被跳过并继续下一次迭代你可以使用continue...

因此,它们应该很少使用...有时它们使代码非常易读和清晰(例如,如果替代方案将是几个级别的嵌套)......大多数时候它们会添加类似的混淆goto.


wag*_*ghe 5

我,为什么你还没有看到它之前的猜测是,continue是那种一个表弟的gotobreak和早期return的功能秒。我们都知道Goto被认为是有害的,因此许多开发人员可能倾向于避免使用它。

对于我来说,我倾向于continue在需要清理一些可能不需要某些值的循环时使用。使用continueI可以跳过这些值,而无需在循环中将“重要”逻辑包含在nested中if

foreach (var v in GetSomeValues())
{
  if (ThisValueIsNotImportant(v)) continue;

  //Do important stuff with the value.
}
Run Code Online (Sandbox Code Playgroud)