【问题标题】:Ternary operator (?) not working三元运算符(?)不起作用
【发布时间】: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

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

【问题讨论】:

  • 我很想将其作为副本关闭。请参阅this、this 或 this。
  • 您的“类似问题”是针对 java 的。尽管这些语言表面上相似,但这并不重要。你想要 C# language spec 而不是 java 规范。
  • mike z,我知道你是对的.. 在这里做什么合适?我应该删除这个问题吗?
  • 如果其他人回答了您的问题,那么删除就可以了。如果还没有回答,请修改它以指出您不理解的内容(您可能希望查看 C# 规范的第 7.14 节)。如果您无法删除,请告诉我,我可以标记为重复。

标签: c# if-statement ternary-operator


【解决方案1】:

这不起作用,因为表达式condition?DateTime.Now: null 无法计算,因为它的类型不清楚。表达式必须在赋值之前求值,问题不在于赋值;它与表达式的评估有关。这就是 if-then 有效而三元运算符无效的原因。

【讨论】:

    【解决方案2】:

    为什么这不起作用?

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

    DateTime 和 null 之间没有隐式转换

    DateTime.Now 的类型为 DateTime。 null 不是有效的 DateTime 值。编译器说它找不到任何可以将 DateTime.Now 和 null 隐式(因为您没有明确指定任何转换)转换为的常见类型。

    但是对于C#中的三元?:运算符,强制要求第二个和第三个操作数可以转换为相同的类型,这也是涉及?:的整个表达式的返回值的类型

    显然,您想要检索 DateTime? 值 - DateTime 值不会隐式转换为 DateTime?,但您可以显式执行此操作:

    DateTime? date = condition ? (DateTime?)DateTime.Now : null;
    

    这样,您告诉编译器将第二个操作数视为DateTime? 类型。第三个操作数null可以隐式转换为DateTime?,这样就没有矛盾了,编译错误也就消失了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2011-08-30
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      相关资源
      最近更新 更多