【问题标题】:IEnumerable not null, but throwing a NullReferenceException on iterationIEnumerable 不为空,但在迭代时抛出 NullReferenceException
【发布时间】:2016-10-12 19:43:01
【问题描述】:

我有一个运行 foreach 的 IEnumerable。在某些情况下,它会在 foreach 行上抛出空引用异常,它说

ienumerable 抛出了 'System.NullReferenceException 类型的异常

if (ienumerable != null)
{
    foreach (var item in ienumerable)
    {
        ......
    }
}

我在 foreach 循环之前进行了 null 检查,并且 iEnumerable 通过了 null 检查,但是当我在其上运行 foreach 循环时,它会引发 null 引用异常。

【问题讨论】:

  • 您没有向我们提供足够的信息。您的ienumerable 是如何填充的?
  • 请说明如何获得此 IEnumerable。如果您像标签建议的那样使用 linq,则可能是在某处获得空引用但执行不同,您只会在实际执行时看到它
  • IEnumerables 在您迭代它们时进行评估。 IEnumerable 的物品从哪里来?
  • 另一个问题:是循环本身(foreach)还是使用item的循环中的工作?

标签: c# foreach ienumerable nullreferenceexception


【解决方案1】:

迭代器在迭代时几乎可以做任何事情,包括抛出异常。所以基本上,你需要知道来源是什么。例如,这是一个以相同方式抛出的非空迭代器:

var customers = new [] {
    new Customer { Name = "abc" },
    new Customer { },
    new Customer { Name = "def" }
};
IEnumerable<int> lengths = customers.Select(x => x.Name.Length);

直到第二次通过循环才会失败。所以:看看迭代器从何而来,以及迭代器是如何实现的。

纯粹是为了好玩,这里还有一个同样会失败的:

IEnumerable<int> GetLengths() {
    yield return 3;
    throw new NullReferenceException();
}

【讨论】:

  • 如果这被编辑到规范空参考问题的主要答案中会很酷。
【解决方案2】:

您的 ienumerable 中的项目有时为空,

试试这个:

    if (ienumerable != null)
    {
        foreach (var item in ienumerable)
        {
            if(item != null)
            {
               // do stuff
            }

        }
    }

这里有一个例子供大家尝试。

        string[] testStr = new string[] { null, "", "test" };
        foreach (var item in testStr)
        {
            if (item != null)
            {
                Console.WriteLine(item);
            }
            else
            {
                Console.WriteLine("item was null");
            }
        }

        Console.ReadKey();

【讨论】:

  • item.item.item != null
  • 这不会导致在获取下一项时出现IEnumerable 错误描述的行为。
  • @Servy 如果 IEnumerable 是使用 .Where() 或类似名称创建的,并且 where 会引发错误(此答案确定了该问题,但其解决方案无法解决该问题。)跨度>
  • 是的,你是对的,诸如列表之类的可枚举项不能为空,但计数仍为 0。并且 Enumerable 中的每个项目在列出的代码中都没有针对其属性进行空检查多于。更多细节将揭示真相......
  • @ScottChamberlain IEnumerable 中的一个项目是 null 在迭代它时不会导致异常。如果IEnumerable 在尝试生成项目时抛出异常,则在该位置的序列中 is 没有对应的项目;序列错误。在生成项目时,序列出错的可能方式有无数种,但没有一种是“序列中的那个项目是null”。这个答案非常具体地指的是迭代器成功产生空值,这显然不是OP的情况。
猜你喜欢
  • 1970-01-01
  • 2020-10-22
  • 2014-06-15
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2021-01-11
  • 2013-05-30
相关资源
最近更新 更多