gpt4 book ai didi

c# - C#.NET 中的 GOTO 语句

转载 作者:太空狗 更新时间:2023-10-29 22:05:58 24 4
gpt4 key购买 nike

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

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

最佳答案

由于“GOTO block”而不是“goto block;”,它不会编译,即使它是正确的,它也不会编译,因为 C# 规范声明(§8.9.3):

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.

我还发现了一些对我来说很有趣的规范:

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.

和:

A goto statement is executed as follows:

  • If the goto statement exits one or more try blocks with associated finally blocks, >control is initially transferred to the finally block of the innermost try statement. When >and if control reaches the end point of a finally block, control is transferred to the >finally block of the next enclosing try statement. This process is repeated until the >finally blocks of all intervening try statements have been executed.
  • Control is transferred to the target of the goto statement.

后者意味着如果你有

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

Label1:
MethodB();

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

很有道理,但我从来没有想过......

关于c# - C#.NET 中的 GOTO 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1952306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com