【发布时间】:2016-03-30 08:11:48
【问题描述】:
为什么这不起作用?
DateTime? date = condition?DateTime.Now: null; //Error: no implicit conversion between DateTime and null
虽然这样做?
DateTime? date;
if (condition)
{
date = DateTime.Now;
}
else
date = null;
here 可以找到一个有点类似的问题,但我就是无法建立关联。谢谢你的帮助。。
更新:我阅读了 Jon Skeet 推荐的 spec document,上面写着:
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
那么,当使用三元运算符时,即使我指定了变量类型,也会强制转换?
【问题讨论】:
-
您的“类似问题”是针对 java 的。尽管这些语言表面上相似,但这并不重要。你想要 C# language spec 而不是 java 规范。
-
mike z,我知道你是对的.. 在这里做什么合适?我应该删除这个问题吗?
-
如果其他人回答了您的问题,那么删除就可以了。如果还没有回答,请修改它以指出您不理解的内容(您可能希望查看 C# 规范的第 7.14 节)。如果您无法删除,请告诉我,我可以标记为重复。
标签: c# if-statement ternary-operator