4

この投稿からのEricLippertのコメントは次のとおりです。

答えがわかったので、このパズルを解くことができます。到達不能なラベルに到達する到達可能なgotoがあるプログラムを作成してください。– EricLippert7月17日7:17

到達不能なラベルを指す到達可能なgotoを持つコードを作成できません。それも可能ですか?はいの場合、C#コードはどのようになりますか?

注:「goto」がどのように悪いかなどについては議論しないでください。これは理論的な演習です。

4

3 に答える 3

13

私の元の答え:

    try
    {
        goto ILikeCheese;
    }
    finally
    {
        throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");

これは、コンパイラの警告なしです。

    bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }

        return;
    }
    finally
    {
        if (jumping)
            throw new InvalidOperationException("You only have cottage cheese.");
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
于 2009-07-22T19:37:26.260 に答える
0

ちなみに、たとえばこの場合、finally ブロックを使用せずに csharp コンパイラに goto を使用すると、コードは goto のないバージョンに変更されます。

using System;
public class InternalTesting
{
public static void Main(string[] args)
{
  bool jumping = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            jumping = (Environment.NewLine != "\t");
            goto ILikeCheese;
        }
    else{
            return;
    }
    }
    finally
    {
        if (jumping)
{
            //throw new InvalidOperationException("You only have cottage cheese.");
    Console.WriteLine("Test Me Deeply");
}
    }
ILikeCheese:
    Console.WriteLine("MMM. Cheese is yummy.");
}
}

に変わります:

public static void Main(string[] args)
{
    bool flag = false;
    try
    {
        if (DateTime.Now < DateTime.MaxValue)
        {
            flag = Environment.NewLine != "\t";
        }
        else
        {
            return;
        }
    }
    finally
    {
        if (flag)
        {
            Console.WriteLine("Test Me Deeply");
        }
    }
    Console.WriteLine("MMM. Cheese is yummy.");
}
于 2010-03-01T15:42:06.600 に答える
-1
goto cant_reach_me;

try{
cant_reach_me:
}
catch{}

これはコンパイル エラーか実行時エラーのどちらかで、覚えていません。ラベルは try/catch ブロックの外側にある必要があります

于 2010-04-14T20:07:38.793 に答える