【问题标题】:C# skips for loop?C#跳过for循环?
【发布时间】: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));}

标签: c# list loops foreach


【解决方案1】:

在 foreach 语句之前调用...这会在 WriteLine 时导致 System.ArgumentOutOfRangeException

不,这不会导致异常。如果您在空集合上使用 Enumerable.ElementAt,则会引发此异常。这也解释了为什么“跳过”foreach 循环。

ArgumentOutOfRangeException: 索引小于 0 或大于或 等于源中元素的数量。

顺便说一句,你可以简化代码:

var entries = row.ChildNodes
    .Where(item => item.Name.Equals("td"))
    .Select(item => item.InnerText)
    .ToList();

【讨论】:

    【解决方案2】:

    意思是

    var items = row.ChildNodes.Where(y => y.Name.Equals("td"));
    

    是空的。

    foreach (var item in items) 执行但什么也不做。

    【讨论】:

    • 谢谢!我好像忘记检查了。
    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多