为什么可空布尔变量不允许的话(可为空),但也允许的话(可为空==真)? [英] Why do nullable bools not allow if(nullable) but do allow if(nullable == true)?

查看:120
本文介绍了为什么可空布尔变量不允许的话(可为空),但也允许的话(可为空==真)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这code编译:

    static void Main(string[] args)
    {
        bool? fred = true;

        if (fred == true)
        {
            Console.WriteLine("fred is true");
        }
        else if (fred == false)
        {
            Console.WriteLine("fred is false");
        }
        else
        {
            Console.WriteLine("fred is null");
        }
    }

这code做的没有的编译。

This code does not compile.

    static void Main(string[] args)
    {
        bool? fred = true;

        if (fred)
        {
            Console.WriteLine("fred is true");
        }
        else if (!fred)
        {
            Console.WriteLine("fred is false");
        }
        else
        {
            Console.WriteLine("fred is null");
        }
    }

我想如果(booleanEx pression == true)而被认为是一个冗余。为什么不是在这种情况下?

I thought if(booleanExpression == true) was supposed to be a redundancy. Why isn't it in this case?

推荐答案

有没有从隐式转换可空<布尔> 布尔。这里的的距离布尔的隐式转换为可空<布尔> ,这就是发生了什么(在语言方面)的每个在第一个版本的布尔常量。该布尔运算符==(可空<布尔>中可空<布尔> 运营商,然后应用(这是不太一样的对方解除运营商 - 结果却布尔,不是可空<布尔>

There's no implicit conversion from Nullable<bool> to bool. There is an implicit conversion from bool to Nullable<bool> and that's what happens (in language terms) to each of the bool constants in the first version. The bool operator==(Nullable<bool>, Nullable<bool> operator is then applied. (This isn't quite the same as other lifted operators - the result is just bool, not Nullable<bool>.)

在换句话说,EX pression'弗雷德==假的类型是布尔,而EX pression弗来德是类型可空&LT;布尔&GT; 因此你不能用它作为如果EX pression

In other words, the expression 'fred == false' is of type bool, whereas the expression 'fred' is of type Nullable<bool> hence you can't use it as the "if" expression.

编辑:要回答的意见,从未有从可空℃的隐式转换; T&GT; T 和很好的理由 - 转换隐不应该抛出异常,除非你想隐式转换为默认(T)有没有很多东西可以做。

To answer the comments, there's never an implicit conversion from Nullable<T> to T and for good reason - implicit conversions shouldn't throw exceptions, and unless you want null to be implicitly converted to default(T) there's not a lot else that could be done.

此外,如果有的的隐式转换左右逢源轮,一个前pression像可空+非空将是非常混乱的(对于支持+,像 INT )。既+(ΔT1,T)+和(T,T)将可用,这取决于操作数被转换! - 但结果可能非常不同

Also, if there were implicit conversions both ways round, an expression like "nullable + nonNullable" would be very confusing (for types that support +, like int). Both +(T?, T?) and +(T, T) would be available, depending on which operand were converted - but the results could be very different!

我的决定,只有从显式转换可空&LT后面100%; T&GT; T

这篇关于为什么可空布尔变量不允许的话(可为空),但也允许的话(可为空==真)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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