C#执行goto语句后如何返回上一步?

Har*_*isk 0 c#

这是我的代码:

private void Mymethod()
{
    if(animal == "Dog")
    {
        goto LabelMonsters;
    }

    //return here after goto LabelMonsters executes
    if (animal == "Cat")
    {
        goto LabelMonsters;
    }

    //another return here after goto LabelMonsters executes
    if (animal == "Bird")
    {
        goto LabelMonsters;
    }

    //Some long codes/execution here.
    return;

    LabelMonsters:
    //Some Code
}
Run Code Online (Sandbox Code Playgroud)

在我的示例中,我有几个if语句,在第一次执行goto语句之后,我必须返回到我的方法下的下一步.我试过继续但不工作.执行必须持续到最后.

Jcl*_*Jcl 5

你不能.goto是一张单程票.虽然在某些情况下使用goto 可能是"正确的",但我会说不在这一个......为什么你不这样做呢?

private void LabelMonsters()
{
  // Some Code
}

private void Mymethod()
{
    if(animal=="Dog")
    {
        LabelMonsters();
    }
    if (animal=="Cat")
    {
        LabelMonsters();
    }
    if (animal == "Bird")
    {
        LabelMonsters();
    }
    // Some long codes/execution here.
}
Run Code Online (Sandbox Code Playgroud)

当然,这段代码是等价的:

private void Mymethod()
{
    if(animal=="Dog" || animal=="Cat" || animal == "Bird")
    {
        // Some code
    }
    // Some long codes/execution here.
}
Run Code Online (Sandbox Code Playgroud)

但我不会把任何事情视为理所当然,因为我不知道你的代码在做什么(它可能会改变animal)