简体   繁体   中英

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. I tried continue but not working. The execution must continue up to the end.

You can't. goto is a one-way ticket. 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?

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 )

Short course in programming: DO NOT use goto.

For a fuller flavor, combine a method with a switch statement:

 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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