C#循环 - 突破与继续 [英] C# loop - break vs. continue

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

问题描述

在一个C#(随时回答其他语言)环路,有什么突破,并继续为手段,以退出循环的结构,并进入下一个迭代的区别?

\r
\r

例如:

\r
\r

 的foreach(在myTable.Rows的DataRow行)结果{结果,如果(someConditionEvalsToTrue){搜索结果打破; //这是什么,并继续的区别结果//继续;结果}}搜索结果 

解决方案

将退出循环完全,继续只会跳过当前迭代。

例如:

 的for(int i = 0;我小于10;我++){
    如果(我== 0){
        打破;
    }    DoSomeThingWith(ⅰ);
}

突破将导致循环退出的第一次迭代 - DoSomeThingWith 将永远不会被执行。这个位置:

 的for(int i = 0;我小于10;我++){
    如果(我== 0){
        继续;
    }    DoSomeThingWith(ⅰ);
}

不会执行 DoSomeThingWith I = 0 ,但循环将继续 DoSomeThingWith 将用于执行 I = 1 I = 9

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?

Example:

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

解决方案

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

For example:

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

    DoSomeThingWith(i);
}

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);
}

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆