【问题标题】:Checking for uninitialized DateTime properties?检查未初始化的 DateTime 属性?
【发布时间】:2022-08-02 17:37:34
【问题描述】:

我有一个具有许多属性的类,其中两个是日期:

public class AchFile
{
    public DateTime FileDate { get; set; }
    public DateTime EffectiveDate { get; set; }
    // other properties

    public int Insert()
    {
        //Set file date
        if (FileDate == null)
        {
            FileDate = DateTime.Today;
        }

        //Set effective date
        if (EffectiveDate == null)
        {
            EffectiveDate = ServiceUtil.NextBusinessDay(InterfaceId, FileDate);
        }
            
        return //....
    }
}

当我创建类的实例时,我没有定义EffectiveDateFileDate。如果我调用.Insert(),这会导致问题,因为DateTime 对象不能是null,因此,那些if 语句将无法正确访问。

更新if 语句的最佳方法是什么?

以下内容有意义吗?

// Default value for a DateTime object is MinValue
if (FileDate == FileDate.MinValue)
{
  FileDate = DateTime.Today;
}

if (EffectiveDate == EffectiveDate.MinValue)
{
  EffectiveDate = ServiceUtil.NextBusinessDay(InterfaceId, FileDate);
}

    标签: c#


    【解决方案1】:

    如果DateTime.MinValue 永远不会是普通的这些属性的值,您可以对照它们进行检查。但这感觉有点不愉快,因为它实际上变成了一个神奇的值。

    另一种选择是使属性可以为空:

    public DateTime? FileDate { get; set; }
    public DateTime? EffectiveDate { get; set; }
    

    然后你能够对照null 检查它们,这将是默认值。

    请注意,如果您真的只表示日期,那么如果您使用的是 .NET 6,我建议您使用 DateOnly 类型来明确这一点。

    【讨论】:

    • 感谢您的回答,我实际上正在使用 Framework 4.6。不过,使属性nullable 的选项更有意义。我认为这应该可以解决问题。
    【解决方案2】:

    您可以将DateTime 更改为DateTime?,然后它们可以为空,这似乎是您想要的最准确的表示(一个没有价值的日期)。

    然后你改变:

    ServiceUtil.NextBusinessDay(InterfaceId, FileDate);
    

    ServiceUtil.NextBusinessDay(InterfaceId, FileDate.Value);
    

    但是,如果你想避免 null,那么 default(DateTime)(或者在以后的 C# 版本中只是 default)就是你想要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2021-06-21
      • 2017-03-03
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多