2016-05-31 40 views
0

這裏是我的代碼: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

回答

2

程序設計短期課程:不要使用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 
} 
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

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

+0

@StianStandahl我不會爭辯:-) – Jcl

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 
}