我有一个 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/