1

这段 C# 代码很简单:

这段代码的场景:

当单词匹配时,会导致意外输出:

找到单词 未找到单词 found 的值为: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();
    }
4

2 回答 2

5

goto 语句只是将执行移动到该点。因此,在您的情况下,正在执行 Found,然后正在执行下一行 NotFound。

要使用 goto 解决此问题,您必须有一个类似于 Continue 的第三个 goto。

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();
}
于 2012-10-28T10:34:21.503 回答
1

当 you 时goto Found,所有其余代码都将执行,包括下一条语句。

于 2012-10-28T10:05:28.543 回答