?: 条件运算符的可空类型问题 [英] Nullable type issue with ?: Conditional Operator

查看:32
本文介绍了?: 条件运算符的可空类型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么这在 C#.NET 2.0 中有效:

Could someone explain why this works in C#.NET 2.0:

    Nullable<DateTime> foo;
    if (true)
        foo = null;
    else
        foo = new DateTime(0);

...但这不是:

    Nullable<DateTime> foo;
    foo = true ? null : new DateTime(0);

后一种形式给了我一个编译错误无法确定条件表达式的类型,因为‘<null>’之间没有隐式转换和'System.DateTime'."

The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."

并不是说我不能使用前者,而是第二种风格与我的其余代码更加一致.

Not that I can't use the former, but the second style is more consistent with the rest of my code.

推荐答案

编译器告诉您它不知道如何将 null 转换为 DateTime.

The compiler is telling you that it doesn't know how convert null into a DateTime.

解决方案很简单:

DateTime? foo;
foo = true ? (DateTime?)null : new DateTime(0);

请注意,Nullable 可以写成 DateTime?,这样可以节省大量的输入时间.

Note that Nullable<DateTime> can be written DateTime? which will save you a bunch of typing.

这篇关于?: 条件运算符的可空类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆