为什么我不能在方法的末尾添加goto标签?

Sam*_*Sam 13 c# for-loop goto nested-loops visual-studio-2012

在研究退出嵌套循环的方法后,我决定尝试使用goto,

private void example()
{
    for (int i = 0; i < 100; i++)
    {
        for (int ii = 0; ii < 100; ii++)
        {
            for (int iii = 0; iii < 100; iii++)
            {
                goto exitMethod;
            }                
        }             
    }

exitMethod:
}
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,如果我把goto标签放在方法的最后,Visual Studio 2012(Ultimate)会抱怨(并且它不会编译),

截图

但是,如果我将代码更改为此,

private void example()
{
    for (int i = 0; i < 100; i++)
    {
        for (int ii = 0; ii < 100; ii++)
        {
            for (int iii = 0; iii < 100; iii++)
            {
                goto exitMethod;
            }                
        }             
    }

exitMethod:

    int someUnneededVariable; // Just an example, if I add ANY piece of code the error vanishes.
}
Run Code Online (Sandbox Code Playgroud)

没有出现任何错误(并且编译); 我搜索了我所知道的所有MSDN参考资料,但我找不到任何相关信息.

我知道我可以通过使用轻松解决这个问题return;; 即便如此,我仍然想知道是什么导致了这个错误.

Jon*_*eet 19

标签本身不存在:它标记了一个语句.从C#5规范的8.4节:

带标签的语句允许语句以标签为前缀.块中允许使用带标签的语句,但不允许使用嵌入式语句.

在这种情况下,你的方法结束应用标签-有它是一个标签,没有声明.所以编译器绝对正确拒绝你的代码.

如果您真的想要,可以在其他冗余的返回语句中添加标签:

exitMethod:
    return;
}
Run Code Online (Sandbox Code Playgroud)

......或者只是一个空话,如Irfan所说.但必须有一个声明.

但我不推荐它.只需更改任何goto exitMethod;语句即可return.


Irf*_*fan 9

您可以放置​​空白声明.

尝试:

exitMethod: ;            
Run Code Online (Sandbox Code Playgroud)

但无论如何,如果你真的想从当前方法返回,请使用return语句.如果method有其他返回类型而不是void,

return (type);
Run Code Online (Sandbox Code Playgroud)

除此以外

return;
Run Code Online (Sandbox Code Playgroud)