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

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

问题描述:

这里是我的代码:C#如何在执行goto语句后返回上一步?

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 
} 

在我的例子,我有几个if语句,第一次执行goto语句后,我必须回到我下的方法进行下一步。我尝试继续,但没有工作。执行必须持续到最后。

+2

作为一个方面说明:你可以使用或改三'if'(''||)。 –

+2

您可能想看看“方法”或“功能”。这些允许你执行一个子功能并返回。 – Luaan

+0

学习构造代码而不滥用goto?如果你需要退后一步,为什么不在退货之前以标签之后的代码方式构造代码? – user6144226

程序设计短期课程:不要使用goto。

对于风味更加浓郁,结合了methodswitch声明:

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

    // afterwards... 
} 

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

你不能。 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. 
} 

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

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

但我不会带走任何东西是理所当然的,因为我不知道你的代码做什么(它可能会改变animal做)

+1

我不知道goto在任何情况下是否正确:P –

+0

@StianStandahl我不会争辩:-) – Jcl

为什么不使用方法?

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 
}