三元运算符(?)不工作

Jus*_*Pup 0 c# if-statement ternary-operator

为什么这不起作用?

DateTime? date = condition?DateTime.Now: null; //Error: no implicit conversion between DateTime and null
Run Code Online (Sandbox Code Playgroud)

这样做呢?

DateTime? date;
if (condition)
{
  date = DateTime.Now;
}
else
  date = null;
Run Code Online (Sandbox Code Playgroud)

这里可以找到一个类似的问题,但我无法进行关联.谢谢你的帮助..

更新:我阅读了Jon Skeet推荐的规范文档,它说:

If one of the second and third operands is of the null type and the type of the other is a 
reference type, then the type of the conditional expression is that reference type
Run Code Online (Sandbox Code Playgroud)

那么,当使用三元运算符时,即使我已经指定了变量类型,也会强制进行转换?

O. *_*per 6

为什么这不起作用?

要回答这个问题,我将引用错误消息:

DateTime和null之间没有隐式转换

DateTime.Now是类型的DateTime.null不是有效值DateTime.编译器说,它无法找到任何常见的类型,这两个DateTime.Nownull可能是隐式(因为你没有明确指定任何转换)转换为.

但是,对于?:C#中的三元运算符,必​​须将第二个和第三个操作数转换为相同的类型,这也是整个表达式的返回值的类型.?:

显然,您想要检索一个DateTime?值 - DateTime值不会被隐式转换为DateTime?,但您可以明确地这样做:

DateTime? date = condition ? (DateTime?)DateTime.Now : null;
Run Code Online (Sandbox Code Playgroud)

这样,您告诉编译器将第二个操作数视为类型DateTime?.第三个操作数null可以隐式转换为DateTime?,因此不再存在矛盾,因此编译器错误消失.