C#错误附加信息:枚举已完成

时间:2017-03-26 16:53:18

标签: c# enumerator

这是我第一次使用枚举器界面。 我试图看一下堆栈来查找下一个字符串。 循环是假设循环扔我的标签堆栈,并找出我的堆栈中的标签是否是我正在寻找的标签。一旦堆栈到达堆栈中的最后一个标签,它就会崩溃并在标题中发出错误。列表中的最后一个标记也恰好是lookforthisTag字符串变量的第一个匹配项。我希望while语句在if语句找到匹配时或在比较所有堆栈项时退出。

/*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.    

3 个答案:

答案 0 :(得分:2)

这一行

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

将执行以下逻辑

  • 枚举器是否返回true?如果是则进入循环,否则检查 下一个条件
  • 发现==是真的吗?如果是则进入循环,否则检查下一个条件
  • 我&lt; = 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逻辑 在所显示的代码中似乎没有任何实用程序。变量I将始终等于countOfTags(或仅仅等于tags.Count),因为您不会中断循环并继续直到枚举结束。如果你想知道找到的标签的“位置”,只需增加它。

答案 1 :(得分:1)

我会像这样重写你的条件:

movsb

或者只使用linq:

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

答案 2 :(得分:0)

由于条件或条件,即使enumerator.MoveNext()为假,因此while中的条件也会为真。

可以通过更改条件并使用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);
相关问题