可空布尔值的行为
Behaviour of nullable boolean
为什么第二种情况编译不通过?有没有办法通过重载或其他方式使它工作?
bool b1 = true;
bool? b2 = false;
if (b1) //does compile
{
//do sth.
}
if (b2) //doesn't compile
{
//do sth.
}
if (b2 == true) //does compile
{
//do sth.
}
因为b2不是bool
类型,而是bool?
,相当于Nullable<bool>
.
您应该尝试以下操作:
if (b2.HasValue && b2.Value)
{
// do sth
}
if 语句需要一个布尔值来解析。
您可以使用 Value
属性
if(b2.Value)
当然,您可能也想检查它是否为空..
== true
compiles 因为 ==
(等于)运算符正在评估一个对象是否等同于另一个对象。这并不一定意味着输出将始终正确(我并不是说它也不会)但是您应该将 Nullable<T>
视为 Nullable<T>
并使用适当的属性
b2 的变量应该是 null able.If 你先检查应该是这个变量的前面的值然后再检查 true 或 false。
第二种情况无法编译,因为 if 语句需要一个布尔表达式,但 b2
本身不是一个布尔表达式。也可以为空。
我通常会选择你的第三个选项 (b2 == true
)。如果它是 not null
并且值为 true
.
,则计算结果为 true
换句话说,b2 == true
等同于b2 != null && b2.Value
。
第三个示例之所以有效,是因为提升了运算符。所以:
For the equality operators
== !=
a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.
所以,这就是第三个示例起作用的原因 - 因为所有这些机制都已发明,并且它适用于 所有 可为 null 的类型。
您的第二个示例 可以 工作,但它需要编译器为恰好 one 可空类型执行特殊工作- bool?
。一般来说,每次使用可空类型都执行隐式转换回原始值类型是不合适的。
(上面引自 language specification 的第 7.3.7 节)
为什么第二种情况编译不通过?有没有办法通过重载或其他方式使它工作?
bool b1 = true;
bool? b2 = false;
if (b1) //does compile
{
//do sth.
}
if (b2) //doesn't compile
{
//do sth.
}
if (b2 == true) //does compile
{
//do sth.
}
因为b2不是bool
类型,而是bool?
,相当于Nullable<bool>
.
您应该尝试以下操作:
if (b2.HasValue && b2.Value)
{
// do sth
}
if 语句需要一个布尔值来解析。
您可以使用 Value
属性
if(b2.Value)
当然,您可能也想检查它是否为空..
== true
compiles 因为 ==
(等于)运算符正在评估一个对象是否等同于另一个对象。这并不一定意味着输出将始终正确(我并不是说它也不会)但是您应该将 Nullable<T>
视为 Nullable<T>
并使用适当的属性
b2 的变量应该是 null able.If 你先检查应该是这个变量的前面的值然后再检查 true 或 false。
第二种情况无法编译,因为 if 语句需要一个布尔表达式,但 b2
本身不是一个布尔表达式。也可以为空。
我通常会选择你的第三个选项 (b2 == true
)。如果它是 not null
并且值为 true
.
true
换句话说,b2 == true
等同于b2 != null && b2.Value
。
第三个示例之所以有效,是因为提升了运算符。所以:
For the equality operators
== !=
a lifted form of an operator exists if the operand types are both non-nullable value types and if the result type is bool. The lifted form is constructed by adding a single ? modifier to each operand type. The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operands are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result.
所以,这就是第三个示例起作用的原因 - 因为所有这些机制都已发明,并且它适用于 所有 可为 null 的类型。
您的第二个示例 可以 工作,但它需要编译器为恰好 one 可空类型执行特殊工作- bool?
。一般来说,每次使用可空类型都执行隐式转换回原始值类型是不合适的。
(上面引自 language specification 的第 7.3.7 节)