所以我经常遇到这种情况……Do.Something(…)返回一个空集合,如下所示:

int[] returnArray = Do.Something(...);

然后,我尝试像这样使用这个集合:

foreach (int i in returnArray)
{
    // do some more stuff
}

我只是好奇,为什么foreach循环不能操作一个空集合?在我看来,零次迭代将被一个空集合执行是合乎逻辑的……相反,它抛出一个NullReferenceException。有人知道为什么吗?

这很烦人,因为我使用的api不清楚它们返回什么,所以我最终到处都是if (someCollection != null)。


当前回答

因为在幕后,foreach获取了一个枚举数,等价于:

using (IEnumerator<int> enumerator = returnArray.getEnumerator()) {
    while (enumerator.MoveNext()) {
        int i = enumerator.Current;
        // do some more stuff
    }
}

其他回答

它被回答了很长时间,但我已经尝试以以下方式这样做,以避免空指针异常,可能对使用c#空检查操作符的人有用。

     //fragments is a list which can be null
     fragments?.ForEach((obj) =>
        {
            //do something with obj
        });

简单的回答是“因为编译器设计者就是这么设计的。”但实际上,您的集合对象是空的,因此编译器无法让枚举器循环遍历集合。

如果你真的需要这样做,试试空合并运算符:

int[] array = null;

foreach (int i in array ?? Enumerable.Empty<int>())
{
   System.Console.WriteLine(string.Format("{0}", i));
}

只要写一个扩展方法来帮助你:

public static class Extensions
{
   public static void ForEachWithNull<T>(this IEnumerable<T> source, Action<T> action)
   {
      if(source == null)
      {
         return;
      }

      foreach(var item in source)
      {
         action(item);
      }
   }
}
SPListItem item;
DataRow dr = datatable.NewRow();

dr["ID"] = (!Object.Equals(item["ID"], null)) ? item["ID"].ToString() : string.Empty;

因为在幕后,foreach获取了一个枚举数,等价于:

using (IEnumerator<int> enumerator = returnArray.getEnumerator()) {
    while (enumerator.MoveNext()) {
        int i = enumerator.Current;
        // do some more stuff
    }
}