How to break out of multiple loops at once in C#?

前端 未结 4 1163
遥遥无期
遥遥无期 2021-02-02 04:54

What if I have nested loops, and I want to break out of all of them at once?

while (true) {
    // ...
    while (shouldCont) {
        // ...
        while (sho         


        
相关标签:
4条回答
  • 2021-02-02 05:32

    Goto is only hideous when abused. To drop out of the innermost loop of some nesting it's acceptable. BUT... one has to ask why there is so much nesting there in the first place.

    Short answer: No.

    0 讨论(0)
  • 2021-02-02 05:36

    If you want to break out of an entire method, then use the code below. If you only want to break out of a series of loops within a method without breaking out of the method, then one of the answers that have already been posted will do the job.

    if (TimeToStop)
    {
       return;
    }
    
    0 讨论(0)
  • 2021-02-02 05:37

    Introduce another control flag and put it in all your nested while condition like below. Also replaces the while(true) condition you have with that

    bool keepLooping = true;
    while (keepLooping) {
        // ...
        while (shouldCont && keepLooping) {
            // ...
            while (shouldGo && keepLooping) {
                // ...
                if (timeToStop) { 
                    keepLooping  = false;
                    break; // break out of everything?
                }
            }  
        }
    }
    
    0 讨论(0)
  • 2021-02-02 05:48

    Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.

    0 讨论(0)
提交回复
热议问题