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

前端 未结 4 1173
遥遥无期
遥遥无期 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: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?
                }
            }  
        }
    }
    

提交回复
热议问题