从一个交换机块内打破了foreach循环 [英] Breaking out of a foreach loop from within a switch block
问题描述
你如何跳出foreach循环,而在一个开关组?
通常情况下,你使用break,但如果你使用一个开关块内休息它将只让你出一个开关模块和foreach循环将继续执行:
的foreach(VAR V IN myCollection)将
{
开关(v.id)
{
情况1:
如果(真)
{
打破;
}
打破;
案例2;
打破
}
}
什么我目前在做的时候,我需要打出来的的foreach
,而开关在
块设置布尔
的值在循环放在外面真实,每一次检查该布尔值的的foreach
进入而进入交换机块之前。事情是这样的:
布尔exitLoop;
的foreach(MyCollection中VAR V)
{
如果(exitLoop)破;
开关(v.id)
{
情况1:
如果(真)
{
exitLoop = TRUE;
打破;
}
打破;
案例2;
打破
}
}
这工作,但我一直在想,必须有这样做的更好的方法,我不知道......
编辑:不知道为什么这在.NET中并没有实现真正整洁的方式,它工作在 PHP 一>所提到的@jon_darkstar?
$ i = 0;
而(++ $ I){
开关($ I){
壳体5:
回声在5℃; BR /> \ N的;
突破1; / *退出只有开关。 * /
案例10:
回声在10;退出< BR /> \ N的;
突破2; / *退出开关和一段时间。 * /
默认:
打破;
}
}
您的解决方案是pretty的在这种情况下,许多最常用的选项。话虽这么说,我把你的出口在检查结束:
布尔exitLoop;
的foreach(MyCollection中VAR V)
{
开关(v.id)
{
情况1:
如果(真)
{
exitLoop = TRUE;
}
打破;
案例2;
打破
}
//这个保存的foreach迭代...
如果(exitLoop)破;
}
另一个主要选择是重构code,并拉动switch语句和foreach循环出到一个单独的方法。然后你可以只是返回
从switch语句中。
How do you break out of a foreach loop while within a switch block?
Normally, you use break but if you use a break within a switch block it will just get you out of a switch block and the foreach loop will continue execution:
foreach (var v in myCollection)
{
switch (v.id)
{
case 1:
if (true)
{
break;
}
break;
case 2;
break
}
}
What I'm currently doing when I need to break out of the foreach
while within the switch
block is setting a bool
value placed outside of the loop to true and checking the value of this bool every time the foreach
is entered and before entering the switch block. Something like this:
bool exitLoop;
foreach (var v in myCollection)
{
if (exitLoop) break;
switch (v.id)
{
case 1:
if (true)
{
exitLoop = true;
break;
}
break;
case 2;
break
}
}
This works but I keep thinking there must be a better way of doing this I am unaware of...
EDIT: Wonder why this was not implemented in .NET the really neat way it works in PHP as mentioned by @jon_darkstar?
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
Your solution is pretty much the most common option in this case. That being said, I'd put your exit check at the end:
bool exitLoop;
foreach (var v in myCollection)
{
switch (v.id)
{
case 1:
if (true)
{
exitLoop = true;
}
break;
case 2;
break
}
// This saves an iteration of the foreach...
if (exitLoop) break;
}
The other main option is to refactor your code, and pull the switch statement and foreach loop out into a separate method. You could then just return
from inside the switch statement.
这篇关于从一个交换机块内打破了foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!