为什么我不能在方法末尾添加goto标签? [英] Why can't I add a goto label at the end of a method?

查看:137
本文介绍了为什么我不能在方法末尾添加goto标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

After researching a way to exit a nested loop, I decided to try using 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:
}

但是由于某种原因,如果我在方法的最后放置一个goto标签,Visual Studio 2012(最终版)会抱怨(并且不会编译),

But for some reason, if I put a goto label is at the very end of the method, Visual Studio 2012 (Ultimate) complains (and it won't compile),

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

But if I change my code to this,

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.
}

所有错误均不会出现(并且会编译);我搜索了我所知道的所有MSDN参考,但对此一无所获.

None of the errors appear (and it compiles); I've searched through all the MSDN references that I know of, and I couldn't find anything about this.

我知道我可以通过使用return;轻松解决此问题;即便如此,我仍然想找出导致此错误的原因.

I know that I could easily solve this problem by using return;; even so, I would still like to find out what's causing this error.

推荐答案

标签本身并不存在:它标签了语句.根据C#5规范的8.4节:

A label doesn't exist on its own: it labels a statement. From section 8.4 of the C# 5 spec:

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

A labeled-statement permits a statement to be prefixed by a label. Labeled statements are permitted in blocks, but are not permitted as embedded statements.

在这种情况下,您将在方法的末尾应用标签-没有声明将其标记为 for .因此,编译器绝对可以拒绝您的代码.

In this case, you're applying the label at the end of the method - there's no statement for it to be a label for. So the compiler is absolutely right to reject your code.

如果您确实愿意,可以在否则为多余的return语句中添加标签:

If you really wanted to, you could add a label to an otherwise-redundant return statement:

exitMethod:
    return;
}

...或者如Irfan所建议的只是一个空语句.不过必须有 a 语句.

... or just an empty statement, as suggested by Irfan. There has to be a statement though.

但是我不推荐它.只需将任何goto exitMethod;语句更改为简单的return.

But I wouldn't recommend it. Just change any goto exitMethod; statement to simply return.

这篇关于为什么我不能在方法末尾添加goto标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆