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

例子:

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

当前回答

简单答案:

Break立即退出循环。继续开始处理下一项。(如果有,跳转到for/while的评估行)

其他回答

有很多人不喜欢休息和继续。我最近看到的关于他们的投诉是在道格拉斯·克罗克福德的《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

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

打破

中断将强制循环立即退出。

持续

这与break相反。它没有终止循环,而是立即再次循环,跳过其余的代码。

至于其他语言:

    '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

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

例如:

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

    DoSomeThingWith(i);
}

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

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

    DoSomeThingWith(i);
}

对于i=0,将不执行DoSomeThingWith,但循环将继续,并且对于i=1到i=9,将执行DoSome ThingWith。

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

// 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[已打印],因为会继续