我有一个小问题。当我编译并运行此代码时,在foreach语句迭代之前调用WriteLine方法。当调用WriteLine时,这会导致System.ArgumentOutOfRangeException,因为该元素尚未被foreach循环设置。我认为c#通过代码向下推进,并等待直到for和while循环完成,然后像C++一样向下继续。有人可以向我解释这一点,并告诉我如何在继续执行之前等待foreach循环。C#跳转循环?
谢谢!
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));
}
'foreach循环已经通过迭代之前,这是执行所有items'不,绝对不是。这很可能是'items'为空 –
您是否已经调试过,观察变量并逐行查看实际执行的内容? –
检查'Debug.WriteLine(items.Any());' – dovid