2017-03-26 22 views
0

這是我第一次使用枚舉器接口。 我正試着看扔堆棧來查找下一個字符串的出現。 循環假設循環投擲我的標籤堆棧,並找出我的堆棧內的標籤是否是我正在尋找的標籤。一旦堆棧到達堆棧中的最後一個標記,它就會崩潰並在標題中發出錯誤。列表中的最後一個標籤也恰好是lookforthisTag字符串變量的第一個匹配項。我希望while語句在if語句找到匹配或所有堆棧項目進行比較時退出。C#錯誤附加信息:枚舉已完成

/*find next opening tag in stack */ 
int I = 1; 
var enumerator = tags.GetEnumerator(); /// create a enumerator variable 

/// move to the next tag in stack 
while (enumerator.MoveNext() != false || found == true || I <= countofTags)  
{              
     htmlTags currentTag = enumerator.Current; // this line causes error. 
     if (currentTag.open_tag == lookforthisTag) 
     { 
       found = true;         
     } 
I++; 
}///End while.  
+2

爲什麼不使用正常的foreach循環? – Steve

回答

2

此行

while (enumerator.MoveNext() != false || found == true || I <= countofTags)  

將執行以下邏輯

  • 枚舉器是否返回true?如果是,請輸入循環其他檢查 下一個條件
  • 找到==是否爲真?如果是輸入循環,否則檢查下一個條件
  • 是我< = countofTags?如果是進入循環,否則退出循環

正如你可以看到,即使枚舉因爲發現點返回false它進入循環是真實的,但在循環中調用enumerator.Current這個觸發器錯誤消息。

也許你想

while (!found && enumerator.MoveNext() && I <= countofTags) 

認爲這是一個正常foreach循環會做同樣的

htmlTags found = null; 
foreach(htmlTags currentTag in tags) 
{ 
    if (currentTag.open_tag == lookforthisTag) 
    { 
      found = currentTag;         
      break; 
    } 
} 
if(found != null) 
{ 
    // got it... 
} 

或者只是使用LINQ

htmlTags found = tags.FirstOrDefault(x => x.open_tag == lookforthisTag) 
if(found != null) 
{ 
    // you have found your tag. 
} 

我還想提的是,您的I <= countOfTags邏輯 在co中似乎沒有任何實用性顯示。變量I將始終等於countOfTags(或者簡單地等於tags.Count),因爲您不會中斷循環並繼續到枚舉結束。如果你想知道找到的標籤的'位置',只需增加它。

1

我會重寫你的,而條件是這樣的:

while (enumerator.MoveNext() && !found && I < countofTags)  

或者只是使用LINQ:

tags.Single (currentTag == currentTag.open_tag == lookforthisTag) 
0

即使enumerator.MoveNext()由於或條件而成爲假,條件將會成立。

它可能可以通過更改條件來解決,也可以使用break退出循環。 這樣的:

while (enumerator.MoveNext() && I <= countofTags)  
{              
     htmlTags currentTag = enumerator.Current; // this line causes error. 
     if (currentTag.open_tag == lookforthisTag) 
     { 
       found = true; 
       break;       
     } 
I++; 
}///End while. 

但是,首先我不會走這條路。
使用LINQ:

var myItem = tags.FirstOrDefault(currentTag=> currentTag.open_tag == lookforthisTag);