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

C# Error Additional information: The enumeration has already completed

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

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

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

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

或者只使用 linq:

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

这一行

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

会执行下面的逻辑

  • 枚举器 return 是否正确?如果是,则进入循环,否则检查 下一个条件
  • 是否发现==是真的?如果是进入循环,否则检查下一个条件
  • 我 <= countofTags 吗?如果是进入循环,否则退出循环

如您所见,即使枚举器 return 为假,它也会进入循环,因为此时 found 为真,但在循环内调用 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),因为您不会中断循环并继续直到枚举结束。如果您想知道找到的标签的'position',只需将其递增即可。

while 中的条件将为真,即使 enumerator.MoveNext() 为假,因为 or 条件。

它可能可以通过更改条件并使用 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);