我特别了解C#Reference 并且已经分析了为什么我不能在finally块中使用goto语句但是我想知道当我使用方法尝试相同的事情时我最终能够离开finally块但是根据规范我必须不.是不是goto moo和static void moo()做同样的行为,即把我带出最后一块?那么为什么在第一种情况下它不起作用但在第二种情况下工作顺利?
break,continue或goto语句的编译时错误是将控制转移出finally块.当finally块中出现break,continue或goto语句时,语句的目标必须位于同一finally块中,否则会发生编译时错误.
在finally块中发生return语句是编译时错误.
第一个案例与Goto声明.
static void Main(string[] args)
{
try{}
catch (Exception ex){}
finally
{
goto moo;
}
moo:
Console.Write("Hello");
}
Run Code Online (Sandbox Code Playgroud)
方法的第二个案例:它奏效了!
static void Main(string[] args)
{
try{}
catch{}
finally
{
moo();
}
}
static void moo()
{
int x=2, y=3, a=4, b=7;
if (x == y)
return;
else
a = b;
}
Run Code Online (Sandbox Code Playgroud)
GOTO声明通常被认为是一种糟糕的编程习惯,导致程序笨拙.应避免使用它.
Jon*_*eet 15
是不是goto moo和static void moo()做同样的动作,即把我带出最后的块?
不,绝对不是.
goto moo将控件finally完全转移出来.
moo()只是调用方法,但是当方法返回时,你回到了finally块中.
如果你把一个方法放在Console.WriteLine("Still here...")你的moo()方法之后,你会看到它.
| 归档时间: |
|
| 查看次数: |
13349 次 |
| 最近记录: |