【问题标题】:Type of conditional expression cannot be determined because there is no implicit conversion between System.DateTime and null无法确定条件表达式的类型,因为 System.DateTime 和 null 之间没有隐式转换
【发布时间】: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;
}

【问题讨论】:

  • DateTimestruct。它不能分配给null。您需要将其声明为nullable(例如:DateTime? tempDate = ...)或使用其他默认值,例如DateTime.MinValue
  • @RufusL:请参考我的line2,控件可以接受null
  • 哦,我一开始肯定看错了,但问题还是基本一样。三元运算符推断第一部分返回的类型,即DateTime。您仍然需要将tempDate 定义为可为空,或者在三元表达式中将其转换为可为空。

标签: c# expression


【解决方案1】:

问题在于三元运算。您正在将数据类型从 DateTime 更改为可为空的 DateTime。三元运算要求您在冒号前后返回相同的数据类型。做这样的事情会起作用:

someDateTimeControl.Value = (tempDate > DateTime.MinValue) ? (DateTime?)tempDate : null;

【讨论】:

    【解决方案2】:

    将双方都转换为可为空的 DateTime,这样它在双方都返回相同的类型。

    someDateTimeControl.Value = (tempDate > DateTime.MinValue)? (DateTime?)tempDate : (DateTime?)null;
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2013-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多