本文介绍了C# 循环 - 中断与继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

示例:

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

推荐答案

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

break will exit the loop completely, continue will just skip the current iteration.

例如:

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

    DoSomeThingWith(i);
}

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

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

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

    DoSomeThingWith(i);
}

不会为 i = 0 执行 DoSomeThingWith,但是循环会继续并且 DoSomeThingWith 会被执行对于 i = 1i = 9.

Will not execute DoSomeThingWith for i = 0, but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9.

这篇关于C# 循环 - 中断与继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:45