问题描述
在 C#(其他语言可以随意回答)循环中,break
和 continue
之间有什么区别作为离开循环结构的手段,以及进入下一次迭代?
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 = 1
到 i = 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# 循环 - 中断与继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!