1

この C# コードは単純です。

このコードのシナリオ:

単語が一致すると、予期しない出力が発生します。

単語が見つかりました 単語が見つかりません 見つかったの値は次のとおりです: True

単語が一致しない場合、期待される出力が得られます。

単語が見つかりません found の値: 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 のような 3 番目の 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

するとgoto Found、次のステートメントを含め、残りのすべてのコードが実行されます。

于 2012-10-28T10:05:28.543 に答える