如何在C#中将可空的bool?
转换为bool
?
我尝试了使用x.Value
或x.HasValue
...
最终你必须决定null
的布尔值表示方式。如果null
应该是false
,那么可以这样做:
bool newBool = x.HasValue ? x.Value : false;
或者:
bool newBool = x.HasValue && x.Value;
或者:
bool newBool = x ?? false;
x ?? something
,其中something
是一个布尔值,如果x
为null
,则您想要使用它。
示例:
bool? myBool = null;
bool newBool = myBool ?? false;
newBool
将为false。
bool? myBool = null; bool newBool = myBool ?? false;
- CaffGeekNullable{T}
的 GetValueOrDefault()
方法。如果为null,它将返回false。 bool? nullableBool = null;
bool actualBool = nullableBool.GetValueOrDefault();
if (nullableBool.GetValueOrDefault())
。 - Luc Wollants如果你要在if
语句中使用bool?
,我发现最简单的方法是与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.
如果你打算将它转换为布尔值以传递给应用程序的其他部分,那么 Null Coalesce 运算符就是你想要的。
bool? b = ...;
bool b2 = b ?? true; // null becomes true
b2 = b ?? false; // null becomes false
如果你已经检查了 null,只需要值,则访问 Value 属性。
bool? b = ...;
if(b == null)
throw new ArgumentNullException();
else
SomeFunc(b.Value);
最简单的方法是使用空值合并运算符:??
bool? x = ...;
if (x ?? true) {
}
带有可空值的 ??
运算符通过检查提供的可空表达式来工作。如果可空表达式有值,则使用该值,否则将使用 ??
右侧的表达式。
这篇答案是针对当您仅想在条件中测试bool?
的用例。它也可以用于获取普通的bool
。个人认为,这是一种比coalescing operator ??
更易于阅读的替代方法。
如果您想测试一个条件,可以使用以下方法:
bool? nullableBool = someFunction();
if(nullableBool == true)
{
//Do stuff
}
如果bool?
为true,上述条件才成立。
您还可以使用它将bool?
分配给常规的bool
。
bool? nullableBool = someFunction();
bool regularBool = nullableBool == true;
这意味着与
bool? nullableBool = someFunction();
bool regularBool = nullableBool ?? false;
bool? a = null;
bool b = Convert.toBoolean(a);
类似这样:
if (bn.HasValue)
{
b = bn.Value
}
bool b1;
bool? b2 = ???;
if (b2.HasValue)
b1 = b2.Value;
或者您可以使用以下方法测试特定的值:
bool b3 = (b2 == true); // b2 is true, not false or null
这是一个有趣的主题变化。乍一看和第二眼看起来你会认为真分支被执行了。但事实并非如此!
bool? flag = null;
if (!flag ?? true)
{
// false branch
}
else
{
// true branch
}
获得你想要的方式是这样的:
if (!(flag ?? true))
{
// false branch
}
else
{
// true branch
}
VB.NET
中执行以下操作:dim newBool as Boolean = CBool(x)
,那么null
会被转换为false
还是会抛出异常? - Luke T O'BrienLinq
语句的“Where”子句中使用,我无法理解为什么lifted operators
似乎无法在 Linq 中工作(也许只是 VB.NET?)- 我刚刚测试了一下,它确实会抛出一个无效的转换异常。 - Luke T O'Brien