c# - C# 中的三元运算符和 if 语句之间有区别吗?

标签 c# ternary-operator

<分区>

我在处理可为空的 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# 中还有其他运算符。它称为“?:”运算符,发音有点难。也称为“条件”运算符。)

关于c# - C# 中的三元运算符和 if 语句之间有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877773/

相关文章:

c# - 找不到类型或命名空间。但引用文献在那里

javascript - JScript 是否提供三元运算符?

java - 为什么我可以在三元运算中将基本类型设置为 null

ios - 对象发送-自动释放次数过多(iOS5)

c++ - 三元运算的奇怪行为

c# - 为什么 C# 三元运算符不能与委托(delegate)一起工作?

c# - 在 ControlTemplate 中,我想将相同的样式应用于所有 TextBlock

c# - 使用 Entity Framework 的 SQL 查询运行速度较慢,使用了错误的查询计划

javascript - 将当前值的 html.dropdownlist 传递给 Actionlink?

c# - MVC 从远距离相关的多个域模型创建 View 模型