尝试将日期时间变量值设置为空

问题描述

我正在尝试将null的值归因于DateTime类型的变量。

在模型类值中采用的属性

public DateTime? ClosedOn = null;

在控制器端读取它时,我正在使用以下代码

member.ClosedOn = reader[6].ToString().Equals(dbnull.Value)|| reader[6].ToString().Equals("") ? null: Convert.ToDateTime(reader[6].ToString());.

但是我遇到了以下错误

“条件表达式的类型无法确定,因为存在 null和DateTime

之间没有隐式转换

任何想法都会受到赞赏。

解决方法

该消息告诉您编译器无法仅根据null确定类型,但是您可以使用(DateTime?) null

member.ClosedOn = reader[6].ToString().Equals(DBNull.Value) || 
                  reader[6].ToString().Equals("") 
    ? (DateTime?) null
    : Convert.ToDateTime(reader[6].ToString());

类似地,由于null是可为空类型的默认值,因此您还可以使用:default(DateTime?)而不是null

member.ClosedOn = reader[6].ToString().Equals(DBNull.Value) || 
                  reader[6].ToString().Equals("") 
    ? default(DateTime?)
    : Convert.ToDateTime(reader[6].ToString());