Is goto ok for breaking out of nested loops?

后端 未结 10 1840
忘掉有多难
忘掉有多难 2021-01-18 04:33

JavaScript supports a goto like syntax for breaking out of nested loops. It\'s not a great idea in general, but it\'s considered acceptable practice. C# does not directly

10条回答
  •  囚心锁ツ
    2021-01-18 05:08

    It's a bit of a unacceptable practice in C#. If there's no way your design can avoid it, well, gotta use it. But do exhaust all other alternatives first. It will make for better readability and maintainability. For your example, I've crafted one such potential refactoring:

    void Original()
    {
        int i = 0;            
        while(i <= 10)
        {
            Debug.WriteLine(i);
            i++;
            if (Process(i))
            {
                break;
            }
        }
    }
    
    bool Process(int i)
    {
        for(int j = 0; j < 3; j++)
            if (i > 5)
            {
                return true;
            }
        return false;
    }
    

提交回复
热议问题