gpt4 book ai didi

c# - 遍历 List 时出现空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 19:12:58 25 4
gpt4 key购买 nike

我在迭代不可为 null 的对象的集合时遇到 null 异常。

List<ReconFact> facts = new List<ReconFact>();
// ...populating facts

int count = 0;

foreach (var fact in facts)
{
Console.WriteLine(++count);
try
{
context = AddToContext(context, fact, count, 100, true);
}
catch (Exception e)
{
Console.WriteLine(e.Message); // Null Exception Raised at some point
}
}

这怎么可能?我不知道遍历列表可以提供 null 元素是一种正常行为吗?填充列表时是否可以添加空项?

最佳答案

是的,可以添加 nullList<T>其中 T是引用类型。没有什么能阻止某人:

List<ReconFact> facts = new List<ReconFact>();
facts.Add(null);

您可以先简单地检查一下:

foreach (var fact in facts.Where(f => f != null))
// ...

关于c# - 遍历 List<T> 时出现空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19291626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com