C#.NET中的GOTO语句 [英] GOTO statement in C#.NET

查看:514
本文介绍了C#.NET中的GOTO语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

try
{...
block:
....
}
catch{ ..}
GOTO block
...
....
finally{...}

在这种情况下goto会执行吗?

Will goto executes in this case??

推荐答案

它不会因为'GOTO block'而不是'goto block;'而无法编译,即使正确,它也不会因为C#规范而无法编译状态(第8.9.3节):

It won't compile because of 'GOTO block' instead of 'goto block;' and even if it was right it won't compile because C# specifications states (§8.9.3):

goto identifier 语句的目标是带有给定标签的带标签的语句.如果当前函数成员中不存在具有给定名称的标签,或者goto语句不在标签范围内,则会发生编译时错误.该规则允许使用goto语句将控制权移出嵌套作用域,但不能将其转移到嵌套作用域中.

The target of a goto identifier statement is the labeled statement with the given label. If a label with the given name does not exist in the current function member, or if the goto statement is not within the scope of the label, a compile-time error occurs. This rule permits the use of a goto statement to transfer control out of a nested scope, but not into a nested scope.

我也发现了一些对我来说很有趣的规格:

Also I found couple specs interesting for me too:

goto语句不能退出finally块(第8.10节).当goto语句出现在finally块内时,goto语句的目标必须位于同一finally块内,否则会发生编译时错误.

A goto statement cannot exit a finally block (§8.10). When a goto statement occurs within a finally block, the target of the goto statement must be within the same finally block, or otherwise a compile-time error occurs.

并且:

goto语句执行如下:

A goto statement is executed as follows:

  • 如果goto语句退出一个或多个带有关联的finally块的try块,则将控制权最初转移到最里面try语句的finally块.当>并且如果控制到达finally块的终点时,控制将转移到下一个封闭try语句的> finally块.重复此过程,直到执行了所有干预try语句的> finally块为止.
  • 控制权转移到goto语句的目标.

后者意味着如果您有

try
{
    ...
    goto Label1;
}
finally
{
    CloseAll();
}

Label1:
   MethodB();

它将在实际将控制权转移到Label1并执行MethodB()之前调用CloseAll().

it will call CloseAll() before actually transferring control to the Label1 and executing MethodB().

感觉很完美,但我从未想过...

Makes perfect sense, but I never thought about it...

这篇关于C#.NET中的GOTO语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆