【问题标题】:Nullable DateTime? to DateTime convertion doesn't work可空日期时间?到 DateTime 转换不起作用
【发布时间】:2013-09-02 13:05:20
【问题描述】:

我的成员类中有一个 DOB 属性定义为可为空的 DateTime?:

public DateTime? DOB
{
    get
    {
        var o = base.GetPropertyValue("memberDOB");
        if (o == DBNull.Value)
        {
            return null;
        }
        return (DateTime?)o;
    }
    set
    {
        base.SetPropertyValue("memberDOB", value);
    }
}

当值为空并且我试图检查它是否可以为空时 - 它只是一直说强制转换无效:

if((DateTime)_currentProfile.DOB == null)
    txtDOB.Text = _currentProfile.DOB.ToString();

我试过了

TryParse(_currentProfile.DOB.ToString(), out dob)

_currentProfile.DOB == null

_currentProfile.DOB.ToString()

(DateTime)_currentProfile.DOB

它们都不起作用 - 它总是说强制转换无效。

不太明白为什么。

有什么想法吗?谢谢

【问题讨论】:

    标签: datetime casting null nullable type-conversion


    【解决方案1】:

    您不应该像这样将 Nullable DateTime 转换为 DateTime。当它为空时它会中断。

    使用DateTime.HasValue,如果返回true,则使用DateTime.Value

    【讨论】:

      【解决方案2】:

      您正在投射到DateTime,这是一个value type,永远不能是null

      如果您想检查null,请转换为DateTime?,或者更确切地说,不要转换而是直接检查它:

      if(_currentProfile.DOB.HasValue)
          txtDOB.Text = _currentProfile.DOB.ToString();
      

      请注意,如果一个值,您可以使用它。您的原始代码似乎是倒退的。

      【讨论】:

      • 或者:如果 (_currentProfile.DOB != null)
      • @SteveWellens - 当然可以,但是如果您已经有 Nullable<T>,不妨使用内置语义。
      • 当然可以,但是如果您费心让某些东西可以为空,您不妨将其用作可以具有 null 值的东西。
      • @SteveWellens - 我真的对此没有强烈的感觉。风格问题 - 由团队决定并在代码库中保持一致。
      • @Oded 它对 HasValue 属性不起作用,仍然出现错误。我使用了 try{} catch{} 语法,如果 DateTime 为空,则传递另一个值
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 2022-12-03
      • 2014-11-05
      相关资源
      最近更新 更多