C#本例中GOTO如何工作(不符合预期)?

时间:2012-10-28 10:03:17

标签: c# match goto

这个C#代码很简单:

此代码的方案:

当单词匹配时,会产生意外输出:

找到了这个词 找不到这个词 找到的值是:True

当单词不匹配时,会产生预期的输出:

找不到这个词 找到的值是:False

    static void Main()
    {
        string[] words = { "casino", "other word" };

        Boolean found = false;
            foreach (string word in words)
            {
                if (word == "casino")
                {
                    found = true;
                    goto Found;
                }
            }

        if(!found)
        {
            goto NotFound;
        }

    Found: { Console.WriteLine("The word is found"); }
    NotFound: { Console.WriteLine("The word is not found"); }

        Console.WriteLine("The value of found is: {0}", found);

        Console.Read();
    }

2 个答案:

答案 0 :(得分:5)

goto语句只是将执行移动到那一点。所以在你的情况下,正在执行Found,然后正在执行下一行NotFound。

要使用goto修复此问题,您必须使用第3个goto,例如Continue。

static void Main()
{
    string[] words = { "casino", "other word" };

    Boolean found = false;

    foreach (string word in words)
    {
        if (word == "casino")
        {
            found = true;
            goto Found;
        }
    }

    if(!found)
    {
        goto NotFound;
    }

    Found: { Console.WriteLine("The word is found"); goto Continue; }
    NotFound: { Console.WriteLine("The word is not found"); }

    Continue:
    Console.WriteLine("The value of found is: {0}", found);

    Console.Read();
}

我更喜欢这样的事情:

static void Main()
{
    string[] words = { "casino", "other word" };

    Boolean found = false;

    foreach (string word in words)
    {
        if (word == "casino")
        {
            found = true;
            break;
        }
    }

    if(!found)
    {
        Console.WriteLine("The word is not found");
    }
    else
    {
        Console.WriteLine("The word is found");
    }

    Console.WriteLine("The value of found is: {0}", found);

    Console.Read();
}

甚至更好!

static void Main()
{
    string[] words = { "casino", "other word" };

    if (words.Contains("casino"))
    {
        Console.WriteLine("The word is found");
    }
    else
    {
        Console.WriteLine("The word is not found");
    }

    Console.Read();
}

答案 1 :(得分:1)

当你goto Found时,你的所有其余代码都会被执行,包括下一个语句。