为什么条件运算符没有正确地允许使用“null”来赋值为可空类型?

可能重复:
可空类型和三元运算符。 为什么这不起作用?
具有可空类型的条件运算符赋值?

这将无法编译,说明“无法确定条件表达式的类型,因为’System.DateTime’和””之间没有隐式转换

task.ActualEndDate = TextBoxActualEndDate.Text != "" ? DateTime.Parse(TextBoxActualEndDate.Text) : null; 

这很好用

  if (TextBoxActualEndDate.Text != "") task.ActualEndDate = DateTime.Parse(TextBoxActualEndDate.Text); else task.ActualEndDate = null; 

这不起作用,因为编译器不会立即在两端插入隐式转换,而null需要隐式转换才能成为可空类型。

相反,你可以写

 task.ActualEndDate = TextBoxActualEndDate.Text != "" ? DateTime.Parse(TextBoxActualEndDate.Text) : new DateTime?(); 

这只需要一次隐式转换( DateTime to DateTime? )。

或者,您可以投射左侧:

 task.ActualEndDate = TextBoxActualEndDate.Text != "" ? (DateTime?)DateTime.Parse(TextBoxActualEndDate.Text) : null; 

这也只需要一次隐式转换。

条件运算符不会查看返回值的内容。 它只查看要求它们选择的值:DateTime和null。 它不能将这些标识为相同类型的实例(因为null不是有效的DateTime),因此错误。 你和我知道Nullable可以完成这项工作,但不允许条件运算符引入“更大”类型:它只允许查看它在两者之间选择的两种表达式的类型。 (感谢Aaronaught在评论中澄清了这一点以及一个很好的澄清示例。)

要解决此问题,请通过强制转换DateTime为操作员提供一个提示:

 TextBoxActualEndDate.Text != "" ? (DateTime?)(DateTime.Parse(TextBoxActualEndDate.Text)) : null; ^^^^^^^^^^^ 

这是重复的

可空类型和三元运算符:为什么是`? 10:null`禁止?

我的答案

条件运算符不能隐式转换?

给出了与这个问题密切相关的分析。

我还将在4月份与条件运营商发表关于类似问题的博客; 观看博客了解详情。

原因是null是object类型,因此您必须将其强制转换为正确的类型,如下所示:

 task.ActualEndDate = TextBoxActualEndDate.Text != "" ? DateTime.Parse(TextBoxActualEndDate.Text) : ((DateTime?) null); 

最正确的方法(IMO)是这样做的

 task.ActualEndDate = TextBoxActualEndDate.Text != "" ? (DateTime?)(DateTime.Parse(TextBoxActualEndDate.Text) : null); 

我经常以这种方式使用null collaescing运算符。

这可能是您在这种情况下得到的错误:

错误CS0173:无法确定条件表达式的类型,因为”和’int’之间没有隐式转换)

编译器正在解释它不知道如何将null转换为DateTime


固定:

你需要explicitly可能返回nullnullable类型的expression 。 这会奏效

 ((DateTime?) null);