在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将完全停止foreach循环,continue将跳到下一个DataRow。
其他回答
break将完全停止foreach循环,continue将跳到下一个DataRow。
若你们不想使用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
}
至于其他语言:
'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
打破
中断将强制循环立即退出。
持续
这与break相反。它没有终止循环,而是立即再次循环,跳过其余的代码。
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。