简体   繁体   English

C#-switch语句内的goto挂起

[英]C# - goto inside a switch statement hangs

I am using a goto inside of a switch statement to emulate fall through behavior. 我在switch语句中使用goto来模拟行为下降。

My switch statement is using an enum to determine which case to use. 我的switch语句使用一个enum来确定要使用哪种情况。 When the case that contains the goto is executed, the execution hangs at that point and the hosting process starts to use a lot more cpu. 当执行包含goto的case时,执行将在此时挂起,并且托管进程开始使用更多的cpu。

My code looks something like the following: 我的代码如下所示:

switch (myEnum)
{
    case HostClass.EnumType.var1: goto case HostClass.EnumType.var2;
    case HostClass.EnumType.var2: myint = 3; break;
    default: break;
}

Why does my switch statement hang on a goto? 为什么我的switch语句挂在goto上? Reading online, this seems to be a common pattern. 在线阅读,这似乎是一种常见的模式。

Removing the goto fixes it, but I dont understand why. 删除goto可以解决此问题,但是我不明白为什么。

You don't need the goto . 您不需要goto Just do this: 只要这样做:

switch (myEnum)
{
    case HostClass.EnumType.var1:
    case HostClass.EnumType.var2: 
        myint = 3; break;
    default: break;
}

Update 更新资料

OK, so the reason (I believe) it doesn't work is because you need a place to goto . OK,所以原因(我相信)它不工作是因为你需要一个地方 goto For example: 例如:

for(var i = 0; i < 100; i+=1)
{
    if(i == 50)
    {
        goto Outer;
    }
}

Outer:
Console.WriteLine("Done");

This is a very contrived example. 这是一个非常人为的例子。

I don't think this explains why your code hangs. 我不认为这可以解释您的代码为什么挂起。 The only thing I can think of is that the goto is waiting for an address? 我唯一想到的就是goto正在等待地址?

As mentioned in the comments by NeilP, You can only fall through on empty case-statements. 如NeilP的评论中所述,您只能陷入空的案例陈述中。 This still doesn't explain why your code hangs on 'goto'. 这仍然不能解释为什么您的代码挂在“ goto”上。 It shouldn't. 不应该这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM