【发布时间】:2020-10-22 16:37:48
【问题描述】:
我在我的代码中遇到了与下面代码中类似的情况。问题是由于某种原因在 foreach 循环中迭代会抛出 NullReferenceException。
我的问题是,为什么会这样?
如果我自己创建了返回空元素的迭代器,foreach 会处理它,而只需 prints 空行。
以下代码的结果是:test, test, NullReferenceException。
using System;
using System.Collections.Generic;
using System.Linq;
public class NestedB
{
public string Test {get;set;}
}
public class NestedA
{
public List<NestedB> NestedCollection {get;set;}
}
public class Program
{
public static void Main()
{
var listOfA = new List<NestedA>
{
new NestedA
{
NestedCollection = new List<NestedB>
{
new NestedB {Test = "test"},
new NestedB {Test = "test"}
}
},
new NestedA ()
};
var listOfB = listOfA.SelectMany(x => x.NestedCollection);
foreach (var item in listOfB)
{
if (item != null)
{
Console.WriteLine(item.Test);
}
}
}
}
堆栈跟踪:
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
at Program.Main()
Command terminated by signal 6
【问题讨论】:
-
@SirRufo 不,我知道 NullReferenceException 是什么,但我不知道为什么会这样。
-
阅读该链接的答案,您就会知道如何解决它
标签: c# .net exception nullpointerexception