问题描述
这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
这篇关于为什么可空布尔变量不允许的话(可为空),但也允许的话(可为空==真)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!