c# finally 块中的 goto vs 方法

goto vs method in finally block in c#

我特别了解 C# Reference 并分析了为什么我不能在 finally 块中使用 goto 语句但我想知道当我尝试使用方法做同样的事情时我终于能够离开最后阻止但根据规范我不能。 goto moostatic void moo() 不是在做同样的事情吗?那么,为什么在 first 情况下它不工作但在 second 情况下工作顺利?

It is a compile-time error for a break, continue, or goto statement to transfer control out of a finally block. When a break, continue, or goto statement occurs in a finally block, the target of the statement must be within the same finally block, or otherwise a compile-time error occurs.

return 语句出现在 finally 块中是一个编译时错误。

第一个带有 Goto 语句的 Case。

static void Main(string[] args)
            {
                try{}
                catch (Exception ex){}
                finally
                {
                    goto moo;
                }
            moo:
                Console.Write("Hello");
            }

方法的第二种情况:有效!

 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;
        }

GOTO 语句通常被认为是导致程序笨拙的不良编程习惯。应避免使用它。

Isn't the goto moo and static void moo() doing the same act i.e taking me out of finally block?

不,绝对不是。

goto moo 会将控制完全移出 finally 块。

moo() 只是调用方法,但是当方法 returns 你又回到了 finally 块。

如果您在 moo() 方法之后放置 Console.WriteLine("Still here..."),您会看到它。