如果找到无效记录,如何安全地返回null?

时间:2016-04-12 22:31:06

标签: c# nullable

我有这段代码:

private static QueuedReports GetSingleReportForUnit(string unit, int RptID, DateTime nextExDate)
{
    ReportSchedule rs = ReportSchedulerSQL.GetReportSchedulerRecord(unit, RptID);
    DateTime d8 = new DateTime(0001, 1, 1); //DateTime.Now.AddYears(1);
    if (rs.NextExecution.Date == d8.Date)
    {
        ;// return null; <= I get, "cannot access a closed stream" with this
    }
    QueuedReports qr = new QueuedReports();
    qr.Unit = unit;
    qr.ReportName = GetReportNameForID(RptID);
    List<String> emailAddresses = ReportSchedulerSQL.GetEmailAddressesForUnitRpt(unit, RptID);
    qr.AllEmailAddresses = string.Join(",", emailAddresses.ToArray());
    qr.NextExecution = nextExDate; 
    qr.NextExecutionsBeginDateArg = GetNextExecutionsBeginDateArg(unit, RptID, nextExDate);
    qr.NextExecutionsEndDateArg = GetNextExecutionsEndDateArg(unit, RptID, nextExDate);
    return qr;
}

...从这里调用:

private static IEnumerable<QueuedReports> GetAllFutureReportsForUnit(string unit, int RptID, DateTime finalDate)
{
    List<QueuedReports> listToReturn = new List<QueuedReports>();
    DateTime currentDate = DateTime.Now;
    while (currentDate <= finalDate)
    {
        currentDate = ReportSchedulerConstsAndUtils.GetNextDateForUnitReportAfter(unit, RptID, currentDate);
        var qr = GetSingleReportForUnit(unit, RptID, currentDate);
        listToReturn.Add(qr);
    }
    return listToReturn;
}

如果在GetSingleReportForUnit()中找到有效记录,也就是说,除了“0001,1,1”之外的值的“NextExecution”,一切都很好;但是,如果没有,我尝试返回null编译,但在运行时因“无法访问已关闭的流”而失败

当无效日期(第1年1月1日)居住在rs.NextExecution时,如何将GetSingleReportForUnit()的执行短路?

QueuedReports是一个自定义类:

public class QueuedReports
{
    public string Unit { get; set; }
    public string ReportName { get; set; }
    public DateTime NextExecution { get; set; }
    public string AllEmailAddresses { get; set; }
    public DateTime NextExecutionsBeginDateArg { get; set; }
    public DateTime NextExecutionsEndDateArg { get; set; }
}

为什么返回null的行为会尝试访问流? AFAICT,此代码中没有任何流,所以WTH?

1 个答案:

答案 0 :(得分:1)

这完全取决于rs.NextExecution正在做什么以及它是如何工作的。如果在那里打开某种流并且它无法返回具有Date属性的对象,那么你的if语句将无法正常工作。

您可以使用try catch块来捕获正在抛出的异常,并在catch语句块中返回null。您可以检查该流是否在该NextExecution对象中仍然有效,而不是检查日期属性是否可用。