在C#循环中,中断和继续作为离开循环结构并进入下一次迭代的方法有什么区别?

例子:

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

当前回答

所有人都给出了很好的解释。我仍然在发布我的答案,只是想举个例子,如果这有帮助的话。

// 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] ";
}

以下是输出:

0[打印]1[打印]2[打印]

因此,当i==3时,3[打印]和4[打印]将不会显示,因为有中断

//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] ";
}

以下是输出:

0[打印]1[打印]2[打印]4[打印]

因此,当i==3时,不会显示3[已打印],因为会继续

其他回答

至于其他语言:

    'VB
    For i=0 To 10
       If i=5 then Exit For '= break in C#;
       'Do Something for i<5
    next
     
    For i=0 To 10
       If i=5 then Continue For '= continue in C#
       'Do Something for i<>5...
    Next

有很多人不喜欢休息和继续。我最近看到的关于他们的投诉是在道格拉斯·克罗克福德的《JavaScript:好零件》中。但我发现,有时使用其中一个确实会简化事情,特别是当您的语言不包含do-while或do-wil循环样式时。

我倾向于使用插入循环来搜索列表中的内容。一旦被发现,就没有继续下去的意义,所以你最好退出。

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

当轮询某人或某物的有效响应时,break语句也很有用。而不是:

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

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

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

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

Do:
    Ask a question
    Until the answer is valid

不需要重复,也不需要中断。

要理解这一点,一个非常简单的方法是在每个关键字后面加上单词“loop”。如果这些术语只是像日常用语一样阅读,那么它们现在就有意义了。

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

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

请让我说明一点:请注意,既不添加中断,也不添加继续,将恢复您的程序;也就是说,我被某个错误捕获,然后在记录它之后,我想继续处理,下一行之间还有更多的代码任务,所以我就让它失败了。

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

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

像这样工作

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

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

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

    printf("%d", i);
}

像这样工作

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

    printf("%d", i);

    CONTINUE:;
}