C＃循环 - 中断与继续

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

15 个答案:

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

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

DoSomeThingWith(i);
}
``````

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

DoSomeThingWith(i);
}
``````

`break` 循环 - 循环已中断并停止。

`continue` 循环 - 循环继续执行下一次迭代。

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

``````for(i = 0; i < 10; i++)
{
if(i == 2)
goto BREAK;
}
BREAK:;
``````

``````for(i = 0; i < 10; i++)
{
if(i == 2)
continue;

printf("%d", i);
}
``````

``````for(i = 0; i < 10; i++)
{
if(i == 2)
goto CONTINUE;

printf("%d", i);

CONTINUE:;
}
``````

`break`会完全停止`foreach`循环，`continue`会跳到下一个`DataRow`

何时使用break vs continue？

1. 休息 - 就像分手一样。很伤心，你们分手了。
1. 继续 - 意味着您今天要给予休息并明天将其全部排序（即跳过当前的迭代）！

``````Ask a question
``````

``````While True:
break
``````

``````Do:
``````

``````// 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 [已打印]

``````//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 [已打印]

<强>额

``````foreach(var i in Enumerable.Range(1,3))
{
Console.WriteLine(i);
}
``````

``````foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
break;

Console.WriteLine(i);
}
``````

``````foreach(var i in Enumerable.Range(1,3))
{
if (i == 2)
continue;

Console.WriteLine(i);
}
``````

``````a = 5
while a < 10
a + 1
end
``````

``````a = 5
b = while a < 10
a + 1
end # b is now 10
``````

``````10.times do |x|
puts x
end
``````

break将跳出调用块的代码

``````def timesten
10.times{ |t| puts yield t }
end

timesten do |x|
x * 2
end
# will print
2
4
6
8 ... and so on

timesten do |x|
break
x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped

timesten do |x|
break 5
x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5

timesten do |x|
next 5
x * 2
end
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.
``````

``````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
}
``````

``````'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
``````