c# - 使用单行 `null` 将 'if' 值分配给 Nullable<DateTime>

标签 c# datetime null

我有这样一个类

public class MyClass
{
    public int Id { get; set; }
    public Nullable<DateTime> ApplicationDate { get; set; }
    ....
}

现在我正在尝试填充 MyClass 的对象像这样

DataTable dt = DBHelper.GetDataTable(sql, conn);
DataRow dr = dt.Rows[0];

MyClass oMyClass = new MyClass();
oMyClass.Id = (int)dr["Id"];
oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value ? null : Convert.ToDateTime(dr["AppDate"]); 
//Above line gives an error
....

分配申请日期值会出错

Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'

我在这里错过了什么?

最佳答案

您需要将 null 转换为 DateTime?:

oMyClass.ApplicationDate = dr["ApplDate"] == DBNull.Value 
    ? (DateTime?)null 
    : Convert.ToDateTime(dr["AppDate"]); 

这是因为编译器确定 conditional operator 的结果类型的方式;该行为是设计使然:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

因为 null 本身 is of null type因此没有从它或到它的转换,您需要通过强制转换来帮助编译器。

关于c# - 使用单行 `null` 将 'if' 值分配给 Nullable<DateTime>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855018/

相关文章:

apache-flex - Flex 空整数

ios - RestKit:如何处理空的 response.body?

mysql - SELECT 语句 - 忽略空白列 - 连接表

c# - 使用 json,net 将对象序列化为字典

c# - 在组合框中以其自己的样式显示字体样式

c# - 如何遍历日期范围?

C# 日期时间到 W3CDTF

C# DateTime.Now 精度

c# - 如何在 C# 中返回隐式缩小和扩大的 UInt?

c# - 有没有办法保存 DBSet 中的更改