Use a 'goto' in a switch?

前端 未结 7 1359
别跟我提以往
别跟我提以往 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:21

    C# refuses to let cases fall through implicitly (unless there is no code in the case) as in C++: you need to include break. To explicitly fall through (or to jump to any other case) you can use goto case. Since there is no other way to obtain this behaviour, most (sensible) coding standards will allow it.

    switch(variable)
    {
    case 1:
    case 2:
        // do something for 1 and 2
        goto case 3;
    case 3:
    case 4:
        // do something for 1, 2, 3 and 4
        break;
    }
    

    A realistic example (by request):

    switch(typeOfPathName)
    {
    case "relative":
        pathName = Path.Combine(currentPath, pathName);
        goto case "absolute";
    
    case "expand":
        pathName = Environment.ExpandEnvironmentVariables(pathName);
        goto case "absolute";
    
    case "absolute":
        using (var file = new FileStream(pathName))
        { ... }
        break;
    
    case "registry":
        ...
        break;
    }
    
    0 讨论(0)
提交回复
热议问题