在C#循环中,中断和继续作为离开循环结构并进入下一次迭代的方法有什么区别?
例子:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
在C#循环中,中断和继续作为离开循环结构并进入下一次迭代的方法有什么区别?
例子:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
当前回答
所有人都给出了很好的解释。我仍然在发布我的答案,只是想举个例子,如果这有帮助的话。
// 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
}
要完全脱离foreach循环,使用break;
要转到循环中的下一个迭代,请使用continue;
如果您在对象集合(如数据表中的行)中循环,并且正在搜索特定的匹配项,则中断非常有用,当您找到匹配项时,无需继续遍历剩余的行,因此您需要中断。
当您完成了循环迭代中所需的任务时,Continue非常有用。通常情况下,你会在一个if之后继续。
至于其他语言:
'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
不幸的是,Ruby有点不同。PS:我的记忆有点模糊,所以如果我错了,请道歉
它有break/next,而不是break/content,它们在循环方面的行为相同
循环(和其他一切一样)是表达式,并“返回”它们所做的最后一件事。大多数时候,从循环中获取返回值是没有意义的,所以每个人都这样做
a = 5
while a < 10
a + 1
end
但是,您可以这样做
a = 5
b = while a < 10
a + 1
end # b is now 10
然而,许多ruby代码通过使用块来“模拟”循环。典型的例子是
10.times do |x|
puts x
end
由于人们更常见的是想用街区的结果来做事,所以这就是变得混乱的地方。break/next在块的上下文中表示不同的东西。
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.
所以是的。Ruby很棒,但它有一些可怕的角落。这是我多年来用过的第二糟糕的:-)
请让我说明一点:请注意,既不添加中断,也不添加继续,将恢复您的程序;也就是说,我被某个错误捕获,然后在记录它之后,我想继续处理,下一行之间还有更多的代码任务,所以我就让它失败了。