C# 循环 — 中断与继续
在 C#(请随意回答其他语言)循环中,作为离开循环结构并转到循环的方式,break
和 continue
之间有什么区别?下一次迭代?
例子:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//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?
Example:
foreach (DataRow row in myTable.Rows)
{
if (someConditionEvalsToTrue)
{
break; //what's the difference between this and continue ?
//continue;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(16)
理解这一点的一个非常简单的方法是将“循环”一词放在每个关键字后面。 如果这些术语像日常短语一样阅读,那么现在它们就有意义了。
break
循环 - 循环被破坏并停止。继续
循环 - 循环继续执行下一次迭代。A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.
break
loop - looping is broken and stops.continue
loop - loop continues to execute with the next iteration.break
将完全退出循环,continue
将跳过当前迭代。例如:
break
将导致循环在第一次迭代时退出 -DoSomeThingWith
将永远不会被执行。While:
这里
继续
跳到for循环的下一次迭代,这意味着DoSomeThingWith
不会在i == 0
时执行。但循环将继续,并且
DoSomeThingWith
将在i == 1
到i == 9
期间执行。break
will exit the loop completely,continue
will just skip the current iteration.For example:
The
break
will cause the loop to exit on the first iteration —DoSomeThingWith
will never be executed.While:
Here
continue
skips to the next iteration of the for-loop, meaningDoSomeThingWith
will not execute fori == 0
.But the loop will continue and
DoSomeThingWith
will be executed fori == 1
toi == 9
.有不少人不喜欢
break
和continue
。 我最近看到的关于它们的抱怨是 Douglas Crockford 的《JavaScript:The Good Parts》。 但我发现有时使用其中之一确实可以简化事情,特别是如果您的语言不包含do-while
或do-until
样式的循环。我倾向于在循环中使用
break
来搜索列表中的内容。 一旦发现,就没有继续下去的意义,所以你还不如退出。在对列表中的大多数元素执行某些操作时,我使用
continue
,但仍想跳过一些元素。在轮询某人或某事的有效响应时,break 语句也很方便。 而不是:
您可以消除一些重复并使用:
我之前提到的
do-until
循环是针对该特定问题的更优雅的解决方案:没有重复,也没有
break
也需要。There are more than a few people who don't like
break
andcontinue
. The latest complaint I saw about them was in JavaScript: The Good Parts by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include ado-while
ordo-until
style of loop.I tend to use
break
in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.I use
continue
when doing something with most elements of a list, but still want to skip over a few.The
break
statement also comes in handy when polling for a valid response from somebody or something. Instead of:You could eliminate some duplication and use:
The
do-until
loop that I mentioned before is the more elegant solution for that particular problem:No duplication, and no
break
needed either.break
将完全停止foreach
循环,continue
将跳到下一个DataRow
。break
would stop theforeach
loop completely,continue
would skip to the nextDataRow
.break 导致程序计数器跳出最内层循环的范围 工作
原理如下
continue 跳转到循环末尾。 在 for 循环中, continue 跳转到增量表达式。
像这样工作
break causes the program counter to jump out of the scope of the innermost loop
Works like this
continue jumps to the end of the loop. In a for loop, continue jumps to the increment expression.
Works like this
何时使用中断与继续?
(老生常谈的故事 ́́\(ツ)/́́ 和图片只是为了帮助你记住......希望你永远不会忘记)
抱怨警报:
不知道为什么使用这些词。 如果您想
跳过
迭代,为什么不使用skip
一词而不是继续
呢? 如果给出正确的名称,整个堆栈溢出问题和成千上万的开发人员都不会感到困惑。)When to use break vs continue?
(Corny stories ¯¯\(ツ)/¯¯ and pics solely to help you remember...hopefully you'll never forget)
Gripe Alert:
No idea why those words are being used. If you want to
skip
the iteration, why not use the wordskip
instead ofcontinue
? This entire Stack overflow question and 1000s of developers would not be confused if the proper name was given.)简单答案:
Break立即退出循环。
继续开始处理下一个项目。 (如果有的话,跳转到for/while的求值行)
Simple answer:
Break exits the loop immediately.
Continue starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)
Break
Break 强制循环立即退出。
继续
这与中断相反。 它没有终止循环,而是立即再次循环,跳过其余代码。
Break
Break forces a loop to exit immediately.
Continue
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.
大家都给出了很好的解释。 我仍然发布我的答案只是为了举例说明是否有帮助。
这是输出:
所以 3[已打印] & 4[Printed] 将不会显示,因为 i == 3 时有中断
这是输出:
所以 3[打印] 不会显示,因为当 i == 3 时有继续
All have given a very good explanation. I am still posting my answer just to give an example if that can help.
Here is the output:
So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3
Here is the output:
So 3[Printed] will not be displayed as there is continue when i == 3
不幸的是,Ruby 有点不同。
PS:我的记忆对此有点模糊,所以如果我错了,
而不是中断/继续,它有中断/下一个,这在循环方面表现相同循环
(就像其他一切一样)是表达式,并且“返回”他们做的最后一件事。 大多数时候,从循环中获取返回值是没有意义的,所以每个人都这样做,
但是您可以这样做
,但是,许多 ruby 代码通过使用块来“模拟”循环。
典型的例子是,
由于人们想要用块的结果做事是更常见的,所以这就是它变得混乱的地方。
在块的上下文中,break/next 意味着不同的东西。
Break 将跳出调用该块的代码,
接下来将跳过该块中的其余代码,并将您指定的内容“返回”给该块的调用者。 如果没有例子,这没有任何意义。
嗯是的。 Ruby 很棒,但它也有一些糟糕的极端情况。 这是我使用它多年以来见过的第二糟糕的:-)
Ruby unfortunately is a bit different.
PS: My memory is a bit hazy on this so apologies if I'm wrong
instead of break/continue, it has break/next, which behave the same in terms of loops
Loops (like everything else) are expressions, and "return" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this
You can however do this
HOWEVER, a lot of ruby code 'emulates' a loop by using a block.
The canonical example is
As it is much more common for people to want to do things with the result of a block, this is where it gets messy.
break/next mean different things in the context of a block.
break will jump out of the code that called the block
next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.
So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)
例如
打印 1、2、3(在单独的行上)。
在 i = 2 处添加中断条件
现在循环打印 1 并停止。
用继续替换中断。
现在循环打印 1 和 3(跳过 2)。
因此,break 停止循环,而 continue 跳到下一次迭代。
By example
Prints 1, 2, 3 (on separate lines).
Add a break condition at i = 2
Now the loop prints 1 and stops.
Replace the break with a continue.
Now to loop prints 1 and 3 (skipping 2).
Thus,
break
stops the loop, whereascontinue
skips to the next iteration.要完全跳出 foreach 循环,请使用 break;
要进入循环中的下一次迭代,请使用继续;
如果您循环遍历对象集合(例如数据表中的行)并且正在搜索特定匹配项,则 Break 非常有用,当您找到该匹配项时,无需继续执行剩余的操作行,所以你想突破。
当您完成循环迭代中所需的操作时,继续非常有用。 通常,您会在 if 之后添加继续。
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
请让我陈述显而易见的事实:请注意,既不添加中断也不添加继续,将恢复您的程序; 即我陷入了某个错误,然后在记录它之后,我想恢复处理,并且下一行之间还有更多代码任务,所以我就让它失败了。
Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.
如果您不想使用 break ,您只需增加 I 的值即可使迭代条件为 false 并且循环将不会在下一次迭代中执行。
if you don't want to use break you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.
由于此处编写的示例对于理解概念来说非常简单,因此我认为查看所使用的 Continue 语句 的更实用版本也是一个好主意。
例如:
我们要求用户输入 5 个唯一的数字,如果该数字已经输入,我们会给他们一个错误,然后继续我们的程序。
假设用户输入的是 1,2,2,2,3,4,5。打印的结果将是:
为什么? 因为每次用户输入列表中已有的数字时,我们的程序都会忽略它并且不会将列表中已有的数字添加到其中。
现在,如果我们尝试相同的代码,但没有 continue 语句,并且假设用户的输入相同,即 1,2,2,2,3,4,5。
输出将是:
为什么? 因为没有 continue 语句让我们的程序知道它应该忽略已经输入的数字。
现在对于 Break 语句,我再次认为最好通过示例来展示。 例如:
这里我们希望我们的程序不断地要求用户输入一个数字。 我们希望循环在用户输入“ok”时终止,并在最后计算所有先前输入的数字的总和并将其显示在控制台上。
这就是在此使用 break 语句的方式例如:
程序会要求用户输入一个数字,直到用户输入“OK”后才会显示结果,为什么?
因为break语句在达到所需条件时完成或停止正在进行的过程。
如果那里没有break语句,程序将继续运行,并且当用户输入“ok”时什么也不会发生。
我建议复制此代码并尝试删除或添加这些语句并亲自查看更改。
Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more practical version of the continue statement being used.
For example:
we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.
lets say the users input were 1,2,2,2,3,4,5.the result printed would be:
Why? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it.
Now if we try the same code but without continue statement and let's say with the same input from the user which was 1,2,2,2,3,4,5.
the output would be :
Why? because there was no continue statement to let our program know it should ignore the already entered number.
Now for the Break statement, again I think its the best to show by example. For example:
Here we want our program to continuously ask the user to enter a number. We want the loop to terminate when the user types “ok" and at the end Calculate the sum of all the previously entered numbers and display it on the console.
This is how the break statement is used in this example:
The program will ask the user to enter a number till the user types "OK" and only after that, the result would be shown. Why?
because break statement finished or stops the ongoing process when it has reached the condition needed.
if there was no break statement there, the program would keep running and nothing would happen when the user typed "ok".
I recommend copying this code and trying to remove or add these statements and see the changes yourself.
至于其他语言:
As for other languages: