この投稿からのEricLippertのコメントは次のとおりです。
答えがわかったので、このパズルを解くことができます。到達不能なラベルに到達する到達可能なgotoがあるプログラムを作成してください。– EricLippert7月17日7:17
到達不能なラベルを指す到達可能なgotoを持つコードを作成できません。それも可能ですか?はいの場合、C#コードはどのようになりますか?
注:「goto」がどのように悪いかなどについては議論しないでください。これは理論的な演習です。
私の元の答え:
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.");
ちなみに、たとえばこの場合、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.");
}
goto cant_reach_me;
try{
cant_reach_me:
}
catch{}
これはコンパイル エラーか実行時エラーのどちらかで、覚えていません。ラベルは try/catch ブロックの外側にある必要があります