【发布时间】:2017-06-22 12:53:50
【问题描述】:
我有一个小问题。当我编译并运行此代码时,在 foreach 语句迭代之前调用 WriteLine 方法。这会在调用 WriteLine 时导致 System.ArgumentOutOfRangeException,因为该元素尚未由 foreach 循环设置。我认为 c# 通过代码向下进展并等到 for 和 while 循环完成,然后像在 c++ 中一样继续向下。有人可以向我解释一下,并告诉我如何等到 foreach 循环再继续执行。
谢谢!
foreach (var row in rows)
{
var items = row.ChildNodes.Where(y => y.Name.Equals("td"));
List<string> entries = new List<string>();
foreach (var item in items)
{
entries.Add(item.InnerText);
}
//This is executed before the foreach loop has iterated through all the items?
Debug.WriteLine(entries.ElementAt(0));
}
【问题讨论】:
-
This is executed before the foreach loop has iterated through all the items不,绝对不是。items很可能是空的 -
你有没有调试过,看看它实际上在做什么,一行一行地观察变量?
-
检查
Debug.WriteLine(items.Any()); -
在循环中调用 WriteLine 看看会发生什么
-
或
Debug.WriteLine(items.Count());像这样:if (items.Any()) {Debug.WriteLine(entries.ElementAt(0));}