Sku*_*ner 55 c# loops continue while-loop
在这个代码示例中,有没有办法从catch块继续外部循环?
while
{
// outer loop
while
{
// inner loop
try
{
throw;
}
catch
{
// how do I continue on the outer loop from here?
continue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 101
更新:这个问题是我关于这个主题的文章的灵感来源.谢谢你这个好问题!
"继续"和"休息"只不过是一个"goto"的愉快语法.显然,通过给他们可爱的名字并将他们的用法限制在特定的控制结构中,他们不再引起"所有人一直都很糟糕"的愤怒.
如果您想要做的是继续到外部,您可以简单地在外部循环的顶部定义标签,然后"转到"该标签.如果您认为这样做并不妨碍代码的可理解性,那么这可能是最方便的解决方案.
但是,我会以此为契机,考虑您的控制流是否会受益于某些重构.每当我在嵌套循环中有条件"break"和"continue"时,我都会考虑重构.
考虑:
successfulCandidate = null;
foreach(var candidate in candidates)
{
foreach(var criterion in criteria)
{
if (!candidate.Meets(criterion))
{ // TODO: no point in continuing checking criteria.
// TODO: Somehow "continue" outer loop to check next candidate
}
}
successfulCandidate = candidate;
break;
}
if (successfulCandidate != null) // do something
Run Code Online (Sandbox Code Playgroud)
两种重构技术:
首先,将内循环提取到一个方法:
foreach(var candidate in candidates)
{
if (MeetsCriteria(candidate, criteria))
{
successfulCandidate = candidate;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
其次,可以消除所有循环吗?如果您正在尝试搜索某些内容而进行循环,则将其重构为查询.
var results = from candidate in candidates
where criteria.All(criterion=>candidate.Meets(criterion))
select candidate;
var successfulCandidate = results.FirstOrDefault();
if (successfulCandidate != null)
{
do something with the candidate
}
Run Code Online (Sandbox Code Playgroud)
如果没有循环,则无需中断或继续!
rya*_*ack 33
while
{
// outer loop
while
{
// inner loop
try
{
throw;
}
catch
{
// how do I continue on the outer loop from here?
goto REPEAT;
}
}
// end of outer loop
REPEAT:
// some statement or ;
}
Run Code Online (Sandbox Code Playgroud)
问题解决了.(什么?你们为什么都给我这么脏的样子?)
Jak*_*son 19
你可以休息一下; 声明.
while
{
while
{
try
{
throw;
}
catch
{
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Continue用于跳回当前循环的顶部.
如果你需要打破更多的级别,你将需要添加某种'if'或使用可怕的/不推荐的'goto'.
Wel*_*bog 10
使用内部while循环交换try/catch结构:
while {
try {
while {
throw;
}
}
catch {
continue;
}
}
Run Code Online (Sandbox Code Playgroud)
不,
我建议将内部循环提取到一个单独的方法中。
while
{
// outer loop
try
{
myMethodWithWhileLoopThatThrowsException()
}
catch
{
// how do I continue on the outer loop from here?
continue;
}
}
}
Run Code Online (Sandbox Code Playgroud)