使用其他类的GetEnumerator时如何处理foreach空异常?

时间:2019-01-15 09:37:56

标签: c# foreach ienumerable ienumerator

我有两个实现IEnumerable的类 A B

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

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

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

在以下示例中:
rootNode 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?
            }
        }

1 个答案:

答案 0 :(得分:5)

不返回 dtLoan = CDate("2019-01-30") dtProcess = CDate ("2020-02-28") 'dtLoan = CDate("2019-01-31") 'dtProcess = CDate ("2020-02-29") 'dtLoan = CDate("2019-02-28") 'dtProcess = CDate ("2020-02-29") if LastDateOfMonth(dtLoan) = dtLoan AND dtProcess = LastDateOfMonth(dtProcess) then response.write " this mean that the Loan date is end of the month, say 31 Jan, 28, 29 of Feb, 31 Feb " response.write " and Process Date is also end of the month " & "<br>" response.write " **** End of the month Loan Date : " & dtLoan & "<br>" response.write " **** End of the month Process Date : " & dtProcess & "<br>" elseif LastDateOfMonth(dtLoan) <> dtLoan AND dtProcess <> LastDateOfMonth(dtProcess) then daysFromEndOfLoanMth = DateDiff("d",LastDateOfMonth(dtLoan),dtLoan) response.write " How many days from end of Loan month: " & daysFromEndOfLoanMth & "<br>" daysFromEndOfProcessMth = DateAdd("d",daysFromEndOfLoanMth,LastDateOfMonth(dtProcess)) response.write " From end of the month Add " & daysFromEndOfLoanMth & " Days = " & daysFromEndOfProcessMth & "<br>" response.write " The date of process : " & dtProcess & "<br>" dtShouldProcess = day(dtLoan) & "/" & Month(dtProcess) & "/" & Year(dtProcess) if isDate(dtShouldProcess) then dtShouldProcess=CDate(dtShouldProcess) else dtShouldProcess=daysFromEndOfProcessMth end if response.write " ** The date of should Process : ** " & dtShouldProcess & "<br>" if dtProcess = dtShouldProcess then 'if dtProcess = daysFromEndOfProcessMth then response.write " **** Loan Date : " & dtLoan & "<br>" response.write " **** Process Date : " & dtProcess & "<br>" end if 'daysFromEndOfProcessMth = DateDiff("d",LastDateOfMonth(dtProcess1),dtProcess1) 'response.write " How many days from Process Date end of the month: " & daysFromEndOfProcessMth & "<br>" end if ,而是使用空集合

null