2016-03-17 37 views
0

我在編程時偶然發現了一個問題,它真的會從goto like結構中受益。考慮下面這個例子:Gotolike結構/改進繼續 - 總是變得邪惡?

//tries to find a solution for a problem 3 times 
//in this process copies elements from old to newList 
foreach (var tryNbr in Util.range(0,3)) 
{ 
    List<A> newList = new List<A>(); 
    List<A> oldList = workList; 
    while(oldList.Count != 0) 
    { 
     List<A> possibleMatched = FINDWITHLINQSTUFF; 
     //try stuff out 

     if(possibleMatches.Count == 0) 
      break; 

     //do more stuff 
    } 

    if(oldList.Any()) 
    { 
     workList = newList; 
     return true; 
    } 
} 

所以這個問題我這裏是,在我的while循環,我需要檢查一些條件,如果這是真的,我想從旁邊的foreach迭代繼續下去,因爲我的整個以前的過程也沒有工作。

由於neighter休息或繼續能做到這一點,我需要檢查我的同時,這是非常容易出錯,如果我以後可能會改變一些東西沒有給予必要的重視後面的額外條件。

有沒有像

goto foreach; 

continue foreach; 

從下一個外部foreach循環延續了contruct? 難道實際上是在這裏使用一個goto一個可行的解決方案(和手動增加計數器

PS:??你有這個代碼的一般結構更好的解決方案

+1

我不確定如果我正確理解問題,但一種方法是定義一個變量bool someConditionMet = false;然後在while循環中將其設置爲true,並在while循環外檢查它的值。 轉到可能是一個解決方案,但通常不建議可讀性的原因,可能調用堆棧的原因(不知道這是在C#中的情況下)。 – Husain

+0

@Husain'goto'在C#中非常安全。可讀性...可能比「goto」更好,而不是本地。當然,它可以使未來的重構變得更加困難 - 特別是,goto不會跨越方法工作(這是件好事)。 – Luaan

+1

Eric Lippert討論了在連接問答中「繼續」本身是否比「goto」更好的優點,並且在他的博客文章中更多地關聯了該答案。 –

回答

1

如果同時結果循環應該控制(即繼續)foreach循環,設計它是這樣:

bool WhateverMethod() 
{ 

    //tries to find a solution for a problem 3 times 
    //in this process copies elements from old to newList 
    foreach (var tryNbr in Util.range(0,3)) 
    { 
     List<A> newList = new List<A>(); 
     List<A> oldList = workList; 

     if (Matched(oldList, newList)) 
      continue; 

     if(oldList.Any()) 
     { 
      workList = newList; 
      return true; 
     } 
    } 
} 

bool Matched(List<A> oldList, List<B> newList) 
{ 
    while(oldList.Count != 0) 
    { 
     List<A> possibleMatched = FINDWITHLINQSTUFF; 
     //try stuff out 

     if(possibleMatches.Count == 0) 
      return false; 

     //do more stuff 
    } 

    return true; // I'm assuming? 
} 

這並沒有解決的goto的使用,或者這個問題:「是不是總是邪惡」,但我會建議轉到爲「總是「或」幾乎總是「不必要

+1

您需要在WhateverMethod中將'return true'更改爲'return',因爲它返回void。 –

+0

@AndyNichols好眼睛,謝謝。 – clarkitect