我有一個小問題。當我編譯並運行此代碼時,在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