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

例子:

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

当前回答

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

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

若你们不想使用break,你们只需要增加I的值,这样就可以使迭代条件为假,并且循环不会在下一次迭代时执行。

for(int i = 0; i < list.Count; i++){
   if(i == 5)
    i = list.Count;  //it will make "i<list.Count" false and loop will exit
}

何时使用中断与继续?

分手-我们将永远离开循环,永远分手。再见。

继续-意味着你今天要休息一下,明天再把它整理好(即跳过当前迭代)!

(Corny故事)\(ツ)/“”和图片,但希望能帮助你记住。

抓握提醒:不知道为什么要使用这些词。如果您想跳过迭代,为什么不使用skip而不是continue?如果给出了正确的名称,整个堆栈溢出问题和1000名开发人员不会感到困惑。)