简体   繁体   English

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

[英]C# How to return to last step after performing goto statement?

Here is my code: 这是我的代码:

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
}

In my sample i have several if statement, after performing goto statement for the first time, I must return to the next step under my method. 在我的示例中,我有几个if语句,第一次执行goto语句后,必须返回到我的方法下的下一步。 I tried continue but not working. 我尝试继续,但不起作用。 The execution must continue up to the end. 执行必须一直持续到最后。

You can't. 你不能 goto is a one-way ticket. goto是单程票。 Although the use of goto may be "correct" in some situations, I'd say not in this one... why don't you do something like this instead? 尽管在某些情况下使用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.
}

Of course, this code would be equivalent: 当然,这段代码是等效的:

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

but I won't take anything for granted, since I don't know what your code is doing (it could be changing animal ) 但我不会认为这是理所当然的,因为我不知道您的代码在做什么(这可能会改变animal

Short course in programming: DO NOT use goto. 编程短期课程:请勿使用goto。

For a fuller flavor, combine a method with a switch statement: 为了使口味更饱满,请将方法switch语句结合使用:

 private void MyMethod()
 {
     switch (animal)
     {
         case "Dog":
         case "Cat":
         case "Bird":
            LabelMonster(animal);
            break;
     }

     // afterwards...
 }

 private void LabelMonster(string animal)
 {
     // do your animal thing
 }

Why dont you use a method? 你为什么不使用一种方法?

public void MyMethod()
{
    if (animal == "Dog" || animal == "Cat" || animal == "Bird") LabelMonsters();
    //Code to run after LabelMonsters or if its not one of that animals
}
void LabelMonsters()
{
    //Your code
}

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

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