可能重复:
Why does .NET foreach loop throw NullRefException when collection is null?
如果目标集合为null,foreach迭代器将抛出异常。
示例:
List<string> names = null;
foreach(var name in names) { /* throws exception */ }它背后的设计思想是什么?不迭代循环而不是.NET框架抛出异常不是很方便吗?
发布于 2012-03-23 23:06:08
通常,空集合表示集合无效。我希望一个空集合不会迭代,但是当我期望一个有效的集合时,空集合会被看作是异常。
Why does .NET foreach loop throw NullRefException when collection is null?
发布于 2012-03-23 23:06:54
我想这背后根本就没有什么概念。如您所知,foreach被添加了很久之后,枚举器和foreach就建立在它之上(*)。
(*) foreach在某种程度上相当于:
var enumerator = someList.GetEnumerator();
while (enumerator.MoveNext())
{
//do something with enumerator.Current
}不能对null的内容运行GetEnumerator。
https://stackoverflow.com/questions/9847528
复制相似问题