编译器错误可能为空的布尔 [英] Compiler Error for Nullable Bool
问题描述
bool? ispurchased = null;
var pospurcahsed= ispurchased ? "1":"2";
其发生异常。
Its generating exception .
无法隐式转换类型'布尔?'为'布尔'。一个明确的
股转换存在(是否缺少强制转换?)
Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
我在做什么错在这里?
感谢您的支持和关注。
What I am doing wrong here? thanks for your support and consideration.
推荐答案
这是不是允许,因为目前还不清楚是指在上下文是什么空的一个条件。
This is not allows because it is unclear what null means in the context of a conditional.
可空布尔
可转换为布尔
明确为了在有条件使用,但如果对象有一个值,如果无效,出现InvalidOperationException
将被抛出。
Nullable Booleans
can be cast to a bool
explicitly in order to be used in a conditional, but if the object has a value if null, InvalidOperationException
will be thrown.
据铸造布尔
前检查HasValue属性是非常重要的。
It is therefore important to check the HasValue property before casting to bool
.
使用像
var pospurcahsed= (ispurchased.HasValue && ispurchased.Value) ?......
可空布尔类似于在SQL中使用的布尔变量类型。以确保该结果由&放大器产生;和|与SQL的三值布尔类型一致,都为运营商提供下列预定义的运算符:
Nullable Booleans are similar to the Boolean variable type used in SQL. To ensure that the results produced by the & and | operators are consistent with SQL's three-valued Boolean type, the following predefined operators are provided:
bool? operator &(bool? x, bool? y)
bool? operator |(bool? x, bool? y)
也可以使用马丁
建议 GetValueOrDefault
[感谢马丁指出它的]
or you can use martin
suggestion GetValueOrDefault
[Thanks to martin to pointing it out ]
GetValueOrDefault方法返回即使的HasValue
属性为false值(不像Value属性,它抛出一个异常)。
The GetValueOrDefault method returns a value even if the HasValue
property is false (unlike the Value property, which throws an exception).
这篇关于编译器错误可能为空的布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!