c# - 使用其他类的 GetEnumerator 时如何处理 foreach 空异常?
问题描述
我 有两个实现. _IEnumerable
A使用B中的 GetEnumerator 。
B是A类的成员。
但是成员B可能为空,所以我添加了空检查。
该问题也在代码示例的注释中说明。应该在另一个分支中放置什么来停止 foreach 空异常?
在以下示例中:
rootNode
is B。
所示函数是A的函数。
B是A的成员。
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?
}
}
解决方案
不要返回null
但使用空集合:
public IEnumerator<BVHNode<BoundingVolumeClass>> GetEnumerator()
{
return rootNode == null
? Enumerable.Empty<BVHNode<BoundingVolumeClass>>().GetEnumerator()
: rootNode.GetEnumerator();
}
推荐阅读
- vb.net - Html 敏捷包无法抓取图像
- jenkins - 如何将 SonarCloud 与 GitHub 和 Jenkins 集成
- typescript - 在 Typescript 中提取静态成员类对象的类型
- google-apps-script - 在 Google 表单上提交时,如何在调试模式下运行 Google App 脚本?
- python - 使用逗号分隔值和红色字体为负值格式化显示在 jupyter 笔记本中的熊猫数据帧
- laravel - 如何与多个结果进行雄辩的关系
- c# - 如何在 Roslyn 推荐的符号中包含关键字和别名?
- javascript - 当我使用 html2canvas 导出甘特仪表板时,为什么我的 PowerPoint 演示文稿是空白的?
- postgresql - Postgresql 数据库中自定义数据类型的列的最大大小是多少?
- ios - 为什么我在这段代码中得到“只能声明实例方法@IBAction”?