首页 > 解决方案 > 使用其他类的 GetEnumerator 时如何处理 foreach 空异常?

问题描述

我 有两个实现. _IEnumerable

A使用B中的 GetEnumerator 。
BA类的成员。

但是成员B可能为空,所以我添加了空检查。

该问题也在代码示例的注释中说明。应该在另一个分支中放置什么来停止 foreach 空异常?

在以下示例中:
rootNodeis B
所示函数是A的函数。
BA的成员。

        public IEnumerator<BVHNode<BoundingVolumeClass>> GetEnumerator()
        {
            if (rootNode != null)
            {
                return rootNode.GetEnumerator();
            }
            else
            {
                return null;
                //return null cause foreach null exception
                //what can be put here to stop it?
            }
        }

标签: c#foreachienumerableienumerator

解决方案


不要返回null但使用空集合

    public IEnumerator<BVHNode<BoundingVolumeClass>> GetEnumerator()
    {
        return rootNode == null
          ? Enumerable.Empty<BVHNode<BoundingVolumeClass>>().GetEnumerator()
          : rootNode.GetEnumerator();
    }

推荐阅读