DateTime tempDate = calculatesomedatetime();
someDateTimeControl.Value = null; //no issue
someDateTimeControl.Value = (tempDate > DateTime.MinValue)? tempDate : null;
由于 System.DateTime 和 null 之间没有隐式转换,无法确定条件表达式的类型
第三行代码抛出了一个错误,我不理解为什么编译器会将比较操作符 (tempDate > DateTime.MinValue)
和 null
的赋值运算符视为同一种类型。因此编译器报错。
然而,如果我像下面这样写,就没有问题:
if(tempDate > DateTime.MinValue)
{
someDateTimeControl.Value = tempDate;
}else
{
someDateTimeControl.Value = null;
}
DateTime
是一个struct
结构体。它不能被赋值为null
。你需要将其声明为可空类型(例如:DateTime? tempDate = ...
),或者使用其他默认值,如DateTime.MinValue
。 - Rufus LDateTime
。你仍然需要将tempDate
定义为可空类型,或在三元表达式中将其转换为可空类型。 - Rufus L