Use a 'goto' in a switch?

前端 未结 7 1365
别跟我提以往
别跟我提以往 2020-12-03 00:25

I\'ve seen a suggested coding standard that reads Never use goto unless in a switch statement fall-through.

I don\'t follow. What exactly would this \'

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 01:19

       public enum ExitAction {
            Cancel,
            LogAndExit,
            Exit
        }
    

    This is neater

    ExitAction action = ExitAction.LogAndExit;
    switch (action) {
        case ExitAction.Cancel:
            break;
        case ExitAction.LogAndExit:
            Log("Exiting");
            goto case ExitAction.Exit;
        case ExitAction.Exit:
            Quit();
            break;
    }
    

    Than this (especially if you do more work in Quit())

    ExitAction action = ExitAction.LogAndExit;
    switch (action) {
        case ExitAction.Cancel:
            break;
        case ExitAction.LogAndExit:
            Log("Exiting");
            Quit();
            break;
        case ExitAction.Exit:
            Quit();
            break;
    }
    

提交回复
热议问题