加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中的三元运算符和if语句之间是否存在差异?

发布时间:2020-12-16 00:14:23 所属栏目:百科 来源:网络整理
导读:参见英文答案 Nullable types and the ternary operator: why is `? 10 : null` forbidden? ????????????????????????????????????9个 ???????????? Conditional operator cannot cast implicitly?????????????????????????????????????3个 我正在使用可以为
参见英文答案 > Nullable types and the ternary operator: why is `? 10 : null` forbidden? ????????????????????????????????????9个
>???????????? Conditional operator cannot cast implicitly?????????????????????????????????????3个
我正在使用可以为空的DateTime对象并遇到一些奇怪的行为.这是一个示例函数:

public DateTime? Weird()
    {
        DateTime check = DateTime.Now;
        DateTime? dt;
        if (check == DateTime.MinValue)
            dt = null;
        else
            dt = Viewer.ActiveThroughUTC.ToLocalTime();

        //this line give a compile error
        dt = (check == DateTime.MinValue) ? (null) : (Viewer.ActiveThroughUTC.ToLocalTime());
        return dt;
    }

据我所知,三元运算符的行应与前四行相同,但VS2010给出了编译错误,表示< null>之间不存在转换.和DateTime(即使有问题的对象是’DateTime?’).有什么我应该知道的关于三元运算符的东西还是这个(喘气?)一个错误?

解决方法

?:运算符中的两个元素应该是相同的类型(但不一定是 – 请参阅下面的详细信息).将null转换为DateTime?:

dt = (check == DateTime.MinValue) ? (DateTime?)null : ...

从spec开始:

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

If X and Y are the same type,then this is the type of the conditional expression.

  • Otherwise,if an implicit conversion (Section 6.1) exists from X to Y,but not from Y to X,then Y is the type of the conditional expression.
  • Otherwise,if an implicit conversion (Section 6.1) exists from Y to X,but not from X to Y,then X is the type of the conditional expression.
  • Otherwise,no expression type can be determined,and a compile-time error occurs.

(有趣的是,它实际上并不称为“三元”运算符.它是一个可能的三元(三值)运算符,我不知道C#中的任何其他运算符.它被称为“?:”运算符,这有点难发音.也称为“条件”运算符.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读