继续嵌套的 while 循环 [英] Continue in nested while loops

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

问题描述

在此代码示例中,有没有办法从 catch 块继续执行外循环?

In this code sample, is there any way to continue on the outer loop from the catch block?

while
{
   // outer loop

   while
   {
       // inner loop
       try
       {
           throw;
       }
       catch 
       {
           // how do I continue on the outer loop from here?
           continue;
       }
   }
}

推荐答案

UPDATE:这个问题是 我关于这个主题的文章.谢谢你的好问题!

UPDATE: This question was inspiration for my article on this subject. Thanks for the great question!

continue"和break"只不过是goto"的一种令人愉快的语法.显然,通过给它们取可爱的名字并将它们的用法限制在特定的控制结构中,它们不再引起所有 goto 一直都是坏的"人群的愤怒.

"continue" and "break" are nothing more than a pleasant syntax for a "goto". Apparently by giving them cute names and restricting their usages to particular control structures, they no longer draw the ire of the "all gotos are all bad all the time" crowd.

如果您想做的是继续到外部,您可以简单地在外部循环的顶部定义一个标签,然后转到"该标签.如果您认为这样做不会妨碍代码的可理解性,那么这可能是最方便的解决方案.

If what you want to do is a continue-to-outer, you could simply define a label at the top of the outer loop and then "goto" that label. If you felt that doing so did not impede the comprehensibility of the code, then that might be the most expedient solution.

但是,我会借此机会考虑您的控制流是否会从一些重构中受益.每当我在嵌套循环中有条件中断"和继续"时,我都会考虑重构.

However, I would take this as an opportunity to consider whether your control flow would benefit from some refactoring. Whenever I have conditional "break" and "continue" in nested loops, I consider refactoring.

考虑:

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

两种重构技术:

首先,将内循环提取到一个方法中:

First, extract the inner loop to a method:

foreach(var candidate in candidates)
{
  if (MeetsCriteria(candidate, criteria))
  { 
      successfulCandidate = candidate;
      break;
  }
}

第二,可以消除所有的循环吗?如果您因为要搜索某些内容而循环,请将其重构为查询.

Second, can all the loops be eliminated? If you are looping because you are trying to search for something, then refactor it into a query.

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
}

如果没有循环,则无需中断或继续!

If there are no loops then there is no need to break or continue!

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

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