c# - IEnumerable 不为 null,但在迭代时抛出 NullReferenceException

标签 c# foreach ienumerable nullreferenceexception

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

ienumerable threw an exception of type 'System.NullReferenceException

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

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

最佳答案

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

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();
}

关于c# - IEnumerable 不为 null,但在迭代时抛出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007040/

相关文章:

c# - DataflowBlock.Complete() 据说会阻止 block 产生更多消息,排队的项目会发生什么?

php - 如何在smarty中打印数组?

c# - 将 IEnumerable<Class> 转换为 List<string>

c# - 是否有将单个项目添加到 IEnumerable<T> 的 Linq 方法?

c# - 为什么 Lookup<TKey, TValue>.Grouping 类不提供相等覆盖?

c# - ASP.NET 持久缓存 ("Lazy loading"风格?)

c# - 从 C# 读取 Azure Blob 存储中的文件

c# - 在aspx.cs(在后面的代码)asp.net中创建RequiredFieldValidator

javascript - 将一个数组分成几个 block

Java foreach 循环不必要的 float 到 int 转换