转换可为空的bool? 布尔
你如何转换一个可空的bool? 在C# bool ?
我已经尝试过x.Value或x.HasValue …
你最终必须决定什么是空的布尔将代表。 如果null应该是false ,你可以这样做:
bool newBool = x.HasValue ? x.Value : false;
要么:
bool newBool = x.HasValue && x.Value;
要么:
bool newBool = x ?? false;
您可以使用空合并运算符 : x ?? something x ?? something ,其中的something是一个布尔值,如果你想使用x为null 。
例:
bool? myBool = null; bool newBool = myBool ?? false;
newBool将是错误的。
您可以使用Nullable{T} GetValueOrDefault()方法。 这将返回false如果为空。
bool? nullableBool = null; bool actualBool = nullableBool.GetValueOrDefault();
最简单的方法是使用空合并运算符: ??
bool? x = ...; if (x ?? true) { }
?? 可以为空的值通过检查提供的可空expression式来工作。 如果可为空的expression式有一个值,那么它的值将被使用,否则它将使用右边的expression式
如果你打算使用bool? 在if语句中,我发现最简单的事情是与true或false进行比较。
bool? b = ...; if (b == true) { Debug.WriteLine("true"; } if (b == false) { Debug.WriteLine("false"; } if (b != true) { Debug.WriteLine("false or null"; } if (b != false) { Debug.WriteLine("true or null"; }
当然,你也可以比较null。
bool? b = ...; if (b == null) { Debug.WriteLine("null"; } if (b != null) { Debug.WriteLine("true or false"; } if (b.HasValue) { Debug.WriteLine("true or false"; } //HasValue and != null will ALWAYS return the same value, so use whatever you like.
如果你打算把它转换成一个bool来传递给应用程序的其他部分,那么Null Coalesce运算符就是你想要的。
bool? b = ...; bool b2 = b ?? true; // null becomes true b2 = b ?? false; // null becomes false
如果您已经检查了空值,并且只需要该值,则可以访问Value属性。
bool? b = ...; if(b == null) throw new ArgumentNullException(); else SomeFunc(b.Value);
完整的方法是:
bool b1; bool? b2 = ???; if (b2.HasValue) b1 = b2.Value;
或者你可以使用testing特定的值
bool b3 = (b2 == true); // b2 is true, not false or null
bool? a = null; bool b = Convert.toBoolean(a);
就像是:
if (bn.HasValue) { b = bn.Value }
这是一个有趣的主题变化。 乍一看,你会假设真正的分支被采取。 不是这样!
bool? flag = null; if (!flag ?? true) { // false branch } else { // true branch }
获得你想要的方式是这样做的:
if (!(flag ?? true)) { // false branch } else { // true branch }
这个答案适用于你只是想testingbool?的用例bool? 在一个条件。 它也可以用来得到一个正常的bool 。 这是一个替代我personnaly发现比联合coalescing operator ??更容易阅读coalescing operator ?? 。
如果你想testing一个条件,你可以使用这个
bool? nullableBool = someFunction(); if(nullableBool == true) { //Do stuff }
以上如果将是真的只有在bool? 是真的。
你也可以使用它来从bool?分配一个常规的bool?
bool? nullableBool = someFunction(); bool regularBool = nullableBool == true;
女巫是一样的
bool? nullableBool = someFunction(); bool regularBool = nullableBool ?? false;