这是 Eric Lippert 在这篇文章中的评论:
既然你知道了答案,你就可以解决这个难题:给我写一个程序,其中有一个可到达的 goto,它指向一个不可到达的标签。– 埃里克·利珀特 7 月 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.");
顺便说一句,如果您使用 goto 编译器,例如对于这种情况,没有 finally 块将代码更改为没有 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 块之外