这是我的代码:
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语句后,我必须返回到我的方法下的下一步。我试过继续但不工作。执行必须持续到最后。
答案 0 :(得分: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.
}
当然,这段代码是等价的:
private void Mymethod()
{
if(animal=="Dog" || animal=="Cat" || animal == "Bird")
{
// Some code
}
// Some long codes/execution here.
}
但我不会理所当然,因为我不知道你的代码在做什么(它可能正在改变animal
)
答案 1 :(得分:2)
编程的短期课程:不要使用goto。
要获得更丰富的味道,请将method与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
}
答案 2 :(得分:1)
为什么不使用方法?
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
}