我有这样一个类
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/