programing

중첩 된 while 루프에서 계속

luckcodes 2021. 1. 16. 20:29

중첩 된 while 루프에서 계속


이 코드 샘플에서 catch 블록의 외부 루프에서 계속 진행할 수있는 방법이 있습니까?

while
{
   // outer loop

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

업데이트 :이 질문은 이 주제에 대한 제 기사에 영감을주었습니다 . 좋은 질문에 감사드립니다!


"continue"와 "break"는 "goto"를위한 ​​즐거운 구문 일뿐입니다. 분명히 그들에게 귀여운 이름을 부여하고 사용을 특정 제어 구조로 제한함으로써, 그들은 더 이상 "모든 고토는 항상 나쁘다"군중의 분노를 끌지 않습니다.

싶은 것은 계속 - 투 - 외부 경우, 당신은 할 수 간단히 "고토"해당 레이블을 외부 루프의 상단에 라벨을 정의합니다. 그렇게하는 것이 코드의 이해를 방해하지 않는다고 생각한다면, 그것이 가장 편리한 해결책 일 것입니다.

그러나 나는 이것을 당신의 제어 흐름이 일부 리팩토링으로부터 이익을 얻을 수 있는지 고려할 기회로 삼고 싶습니다. 중첩 루프에 조건부 "중단"및 "계속"이있을 때마다 리팩토링을 고려합니다.

중히 여기다:

successfulCandidate = null;
foreach(var candidate in candidates)
{
  foreach(var criterion in criteria)
  {
    if (!candidate.Meets(criterion)) // Edited.
    {  // TODO: no point in continuing checking criteria.
       // TODO: Somehow "continue" outer loop to check next candidate
    }
  }
  successfulCandidate = candidate;
  break;
}
if (successfulCandidate != null) // do something

두 가지 리팩토링 기술 :

먼저 내부 루프를 메서드로 추출합니다.

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

둘째, 모든 루프를 제거 할 수 있습니까? 무언가를 검색하려고하기 때문에 루핑하는 경우 쿼리로 리팩터링하십시오.

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
}

루프가 없으면 중단하거나 계속할 필요가 없습니다!


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

문제 해결됨. (뭐 ?? 왜 그렇게 더러운 표정을 짓는거야?)


휴식을 사용할 수 있습니다. 성명서.

while
{
   while
   {
       try
       {
           throw;
       }
       catch 
       {
           break;
       }
   }
}

계속은 현재 루프의 맨 위로 이동하는 데 사용됩니다.

그보다 더 많은 레벨을 돌파해야한다면 일종의 'if'를 추가하거나 두려운 / 권장되지 않은 'goto'를 사용해야합니다.


try / catch 구조를 내부 while 루프로 바꿉니다.

while {
  try {
    while {
      throw;
    }
  }
  catch {
    continue;
  }
}

아니요
. 내부 루프를 별도의 방법으로 추출하는 것이 좋습니다.

while
{
   // outer loop
       try
       {
           myMethodWithWhileLoopThatThrowsException()
       }
       catch 
       {
           // how do I continue on the outer loop from here?
           continue;
       }
   }
}

break내부 루프에서 사용하십시오 .


당신은 단지 외부를 계속할 내부에서 벗어나기를 원합니다.

while
{
   // outer loop

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

이를 수행하는 가장 좋은 방법은 break을 사용하는 것 입니다. 브레이크는 전류 루프를 종료 하고 이 끝나는 위치에서 실행을 계속한다 . 이 경우, 것이다 내부 루프를 종료 하고 루프 동안 외부로 다시 점프 . 코드는 다음과 같습니다.

while
{
   // outer loop

   while
   {
       // inner loop
       try
       {
           throw;
       }
       catch 
       {
           // break jumps to outer loop, ends inner loop immediately.
           break; //THIS IS THE BREAK
       }
   }
}

나는 그것이 당신이 성취하고자했던 것이라고 믿습니다. 맞습니까? 감사!


using System;

namespace Examples
{

    public class Continue : Exception { }
    public class Break : Exception { }

    public class NestedLoop
    {
        static public void ContinueOnParentLoopLevel()
        {
            while(true)
            try {
               // outer loop

               while(true)
               {
                   // inner loop

                   try
                   {
                       throw new Exception("Bali mu mamata");
                   }
                   catch (Exception)
                   {
                       // how do I continue on the outer loop from here?

                       throw new Continue();
                   }
               }
            } catch (Continue) {
                   continue;
            }
        } 
    }

}

}

고유 한 예외 유형 (예 : MyException)을 사용하십시오. 그때:

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

This will work for continuing and breaking out of several levels of nested while statements. Sorry for bad formatting ;)

ReferenceURL : https://stackoverflow.com/questions/1133408/continue-in-nested-while-loops