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

例子:

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

当前回答

break将完全停止foreach循环,continue将跳到下一个DataRow。

其他回答

有很多人不喜欢休息和继续。我最近看到的关于他们的投诉是在道格拉斯·克罗克福德的《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将完全退出循环,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将完全停止foreach循环,continue将跳到下一个DataRow。

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

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

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

要转到循环中的下一个迭代,请使用continue;

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

当您完成了循环迭代中所需的任务时,Continue非常有用。通常情况下,你会在一个if之后继续。