C# 循环 - 中断与继续

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6414/
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-07-31 16:26:53  来源:igfitidea点击:

C# loop - break vs. continue

提问by Seibar

In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration?

在 C#(其他语言可以随意回答)循环中,作为离开循环结构并进入下一次迭代的手段,break 和 continue 之间有什么区别?

Example:

例子:

foreach (DataRow row in myTable.Rows)
{
    if (someConditionEvalsToTrue)
    {
        break; //what's the difference between this and continue ?
        //continue;
    }
}

采纳答案by Michael Stum

breakwill exit the loop completely, continuewill just skipthe current iteration.

break将完全退出循环,continue跳过当前迭代。

For example:

例如:

for (int i = 0; i < 10; i++) {
    if (i == 0) {
        break;
    }

    DoSomeThingWith(i);
}

The break will cause the loop to exit on the first iteration - DoSomeThingWithwill never be executed. This here:

中断将导致循环在第一次迭代时退出 -DoSomeThingWith永远不会被执行。这里:

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;
    }

    DoSomeThingWith(i);
}

Will not execute DoSomeThingWithfor i = 0, but the loop will continueand DoSomeThingWithwill be executed for i = 1to i = 9.

不会执行DoSomeThingWithi = 0,但循环将继续,并DoSomeThingWith为将被执行i = 1i = 9

回答by palmsey

breakwould stop the foreachloop completely, continuewould skip to the next DataRow.

breakforeach完全停止循环,continue会跳到下一个DataRow

回答by JeremiahClark

A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.

理解这一点的一个非常简单的方法是在每个关键字之后放置“循环”一词。如果这些术语只是像日常短语一样阅读,那么它们现在就有意义了。

breakloop - looping is broken and stops.

break循环 - 循环中断并停止。

continueloop - loop continues to execute with the next iteration.

continue循环 - 循环继续执行下一次迭代。

回答by yukondude

There are more than a few people who don't like breakand continue. The latest complaint I saw about them was in JavaScript: The Good Partsby Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a do-whileor do-untilstyle of loop.

有不少人不喜欢breakcontinue。我最近看到的关于它们的抱怨是在JavaScript:Douglas Crockford 的The Good Parts 中。但我发现有时使用其中一个确实可以简化事情,特别是如果您的语言不包含循环do-whiledo-until样式。

I tend to use breakin loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.

我倾向于break在搜索列表的循环中使用。一旦发现,继续下去没有意义,所以你最好退出。

I use continuewhen doing something with most elements of a list, but still want to skip over a few.

continue在处理列表中的大多数元素时使用,但仍然想跳过一些。

The breakstatement also comes in handy when polling for a valid response from somebody or something. Instead of:

break在轮询某人或某事的有效响应时,该语句也派上用场。代替:

Ask a question
While the answer is invalid:
    Ask the question

You could eliminate some duplication and use:

您可以消除一些重复并使用:

While True:
    Ask a question
    If the answer is valid:
        break

The do-untilloop that I mentioned before is the more elegant solution for that particular problem:

do-until我之前提到的循环是针对该特定问题的更优雅的解决方案:

Do:
    Ask a question
    Until the answer is valid

No duplication, and no breakneeded either.

没有重复,也不break需要。

回答by Orion Edwards

Ruby unfortunately is a bit different. PS: My memory is a bit hazy on this so apologies if I'm wrong

不幸的是,Ruby 有点不同。PS:我的记忆有点模糊所以如果我错了请道歉

instead of break/continue, it has break/next, which behave the same in terms of loops

它有 break/next,而不是 break/continue,它们在循环方面的行为相同

Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this

循环(和其他一切一样)是表达式,并且“返回”它们所做的最后一件事。大多数时候,从循环中获取返回值是没有意义的,所以每个人都这样做

a = 5
while a < 10
    a + 1
end

You can however do this

但是你可以这样做

a = 5
b = while a < 10
    a + 1
end # b is now 10

HOWEVER, a lot of ruby code 'emulates' a loop by using a block. The canonical example is

然而,许多 ruby​​ 代码通过使用块来“模拟”循环。典型的例子是

10.times do |x|
    puts x
end

As it is much more common for people to want to do things with the result of a block, this is where it gets messy. break/next mean different things in the context of a block.

由于人们想要用块的结果做事更为常见,这就是它变得混乱的地方。break/next 在块的上下文中意味着不同的东西。

break will jump out of the code that called the block

break 会跳出调用块的代码

next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.

next 将跳过块中的其余代码,并将您指定的内容“返回”给块的调用者。没有例子,这没有任何意义。

def timesten
    10.times{ |t| puts yield t }
end


timesten do |x|
   x * 2
end
# will print
2
4
6
8 ... and so on


timesten do |x|
    break
    x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped

timesten do |x|
    break 5
    x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5

timesten do |x|
    next 5
    x * 2
end 
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.

So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)

是的。Ruby 很棒,但它也有一些糟糕的情况。这是我使用它多年以来见过的第二差的:-)

回答by SemiColon

breakcauses the program counter to jump out of the scope of the innermost loop

break导致程序计数器跳出最内层循环的范围

for(i = 0; i < 10; i++)
{
    if(i == 2)
        break;
}

Works like this

像这样工作

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto BREAK;
}
BREAK:;

continuejumps to the end of the loop. In a for loop, continue jumps to the increment expression.

continue跳到循环的末尾。在 for 循环中, continue 跳转到增量表达式。

for(i = 0; i < 10; i++)
{
    if(i == 2)
        continue;

    printf("%d", i);
}

Works like this

像这样工作

for(i = 0; i < 10; i++)
{
    if(i == 2)
        goto CONTINUE;

    printf("%d", i);

    CONTINUE:;
}

回答by Maltrap

Simple answer:

简单回答:

Breakexits the loop immediately.
Continuestarts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)

Break立即退出循环。
继续开始处理下一个项目。(如果有的话,跳到 for/while 的求值行)

回答by Maltrap

Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.

请让我说明一个明显的问题:注意,既不添加 break 也不添加 continue,将恢复您的程序;即我因为某个错误而被困,然后在记录它之后,我想继续处理,并且在下一行之间有更多的代码任务,所以我就让它失败了。

回答by Pritom Nandy

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

都给出了很好的解释。我仍然发布我的答案只是为了举例说明是否有帮助。

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

这是输出:

0[Printed] 1[Printed] 2[Printed]

0[印刷] 1[印刷] 2[印刷]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

所以 3[Printed] & 4[Printed] 不会显示,因为当 i == 3 时有中断

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

这是输出:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

0[印刷] 1[印刷] 2[印刷] 4[印刷]

So 3[Printed] will not be displayed as there is continue when i == 3

所以 3[Printed] 不会显示,因为当 i == 3 时有 continue

回答by Gopesh Sharma

To break completely out of a foreach loop, breakis used;

要完全脱离 foreach 循环,可以使用break

To go to the next iteration in the loop, continueis used;

要进入循环中的下一次迭代,请使用continue

Breakis useful if you're looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there's no need to continue through the remaining rows, so you want to break out.

如果您循环遍历对象集合(如数据表中的行)并且您正在搜索特定匹配项,则Break很有用,当您找到该匹配项时,无需继续遍历剩余的行,因此您想中断出去。

Continueis useful when you have accomplished what you need to in side a loop iteration. You'll normally have continueafter an if.

当您在循环迭代中完成所需的操作时,Continue很有用。您通常会在if之后继续