【发布时间】:2018-03-14 05:01:34
【问题描述】:
DateTime tempDate = calculatesomedatetime();
someDateTimeControl.Value = null; //no issue
someDateTimeControl.Value = (tempDate > DateTime.MinValue)? tempDate : null;
无法确定条件表达式的类型,因为 System.DateTime 和 null 之间没有隐式转换
第 3 行向我抛出了我不理解的错误,因为比较是 (tempDate > DateTime.MinValue) 和 null 只是赋值。为什么编译器会将此解释为错误?
但是,如果我写成下面,它没有问题
if(tempDate > DateTime.MinValue)
{
someDateTimeControl.Value = tempDate;
}else
{
someDateTimeControl.Value = null;
}
【问题讨论】:
-
DateTime是struct。它不能分配给null。您需要将其声明为nullable(例如:DateTime? tempDate = ...)或使用其他默认值,例如DateTime.MinValue。 -
@RufusL:请参考我的line2,控件可以接受null
-
哦,我一开始肯定看错了,但问题还是基本一样。三元运算符推断第一部分返回的类型,即
DateTime。您仍然需要将tempDate定义为可为空,或者在三元表达式中将其转换为可为空。
标签: c# expression