中断并继续循环封闭的开关块

break and continue in a loop enclosed switch block

所以我有一些如下所示的 C# 代码:

while(condition)
{
    switch(anumber)
    {
        case 0:
            //do something
            break;
        case 1:
            //do something
            break;
        //and so on
    }
}

作为编程新手,我最近在我的词汇表中添加了关键字 continue。在做了一些研究之后,我发现了这个:

the continue statement relates to the enclosing loop

所以我的代码也应该像这样工作:

while(condition)
{
    switch(anumber)
    {
        case 0:
            //do something
            continue;
        //and so on
    }
}

但是编写不产生编译器错误的代码并不是一切。在循环封闭的开关块中使用 continue 是个好主意吗?例如,在性能方面是否存在任何差异,或者这只是两种在语法上不同但在其他方面非常相似的方式来实现相同的结果?

如果switch之后还有一些代码行,continue关键字会忽略它们。试试这个,你会看到不同的:

while(condition)
{
    switch(anumber)
    {
        case 0:
            //do something
            break;
        case 1:
            //do something
            break;
        //and so on
    }
    Console.WriteLine("it's a message");
}

while(condition)
{
    switch(anumber)
    {
        case 0:
            //do something
            continue;
        case 1:
            //do something
            continue;
        //and so on
    }
    Console.WriteLine("it's a message");
}

The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step.

The continue statement applies only to loops, not to a switch statement. A continue inside a switch inside a loop causes the next loop iteration.

以上是针对 C++ 的,但对于 C#,如果您在 Visual Studio 中调试,您在按 F10 时也会看到不同之处。

在调试 break 语句时,它会先转到 switch 语句的结束 '}' 标记,然后再转到 while/for-loop。

在continue的情况下,switch语句的结束'}'标签不会被命中,它会直接进入while/for-loop继续下一次迭代。