c# - 无法确定条件表达式的类型,因为 System.DateTime 和 null 之间没有隐式转换

标签 c# expression

DateTime tempDate = calculatesomedatetime();
someDateTimeControl.Value = null; //no issue
someDateTimeControl.Value = (tempDate > DateTime.MinValue)? tempDate : null;

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

第 3 行抛出这样的错误,我不明白,因为比较是 (tempDate > DateTime.MinValue)null 只是赋值。为什么编译器会将其解释为错误?

但是如果我这样写就没有问题了

if(tempDate > DateTime.MinValue)
{
    someDateTimeControl.Value = tempDate;
}else
{
    someDateTimeControl.Value = null;
}

最佳答案

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

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

关于c# - 无法确定条件表达式的类型,因为 System.DateTime 和 null 之间没有隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537115/

相关文章:

c# - MySql 自上次 NOW() 以来获取更新异步问题

asp.net - <#=#>是什么意思

php - 主机名上的 preg_match

javascript - safari 开发者工具 如何查看来自 iframe 的表达式?

c# - 流利的 NHibernate : How to tell it not to map a base class

c# - 如何在同一个文件中优雅地实现多个字符串替换?

c# - Xamarin IOS 上的推送通知

c# - 创建 GUID 时出现 System.ArgumentNullException

c# - 如何允许用户在 C# 应用程序中定义财务公式

api - Urturn API : command not found