将可为空的 bool? 转换为 bool

如何在 C # 中将可空的 bool?转换为 bool

我试过 x.Value或者 x.HasValue..。

150800 次浏览

您可以使用 空合并运算符: x ?? something,其中 something是一个布尔值,如果 xnull,则需要使用该值。

例如:

bool? myBool = null;
bool newBool = myBool ?? false;

newBool将为假。

比如:

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

您最终必须决定 null bool 将代表什么。如果 null应该是 false,你可以这样做:

bool newBool = x.HasValue ? x.Value : false;

或者:

bool newBool = x.HasValue && x.Value;

或者:

bool newBool = x ?? false;

最简单的方法是使用 null 聚合运算符: ??

bool? x = ...;
if (x ?? true) {


}

具有可空值的 ??通过检查提供的可空表达式来工作。如果可为空的表达式有一个值,它的值将被使用,否则它将使用 ??右侧的表达式

bool? a = null;
bool b = Convert.toBoolean(a);

可以使用 Nullable{T} GetValueOrDefault()方法。如果为空,则返回 false。

 bool? nullableBool = null;


bool actualBool = nullableBool.GetValueOrDefault();

如果您打算在 if语句中使用 bool?,我发现最简单的事情是与 truefalse进行比较。

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

如果您已经检查了 null,并且只想要值,那么访问 Value 属性。

bool? b = ...;
if(b == null)
throw new ArgumentNullException();
else
SomeFunc(b.Value);

这是这个主题的一个有趣的变化。乍一看和第二看,你会认为真正的分支被采取。不是这样的!

bool? flag = null;
if (!flag ?? true)
{
// false branch
}
else
{
// true branch
}

得到你想要的东西的方法是这样做:

if (!(flag ?? true))
{
// false branch
}
else
{
// true branch
}

这个答案适用于您只是想在一个条件中测试 bool?的用例。它也可以用来得到一个正常的 bool。这是一个选择,我个人发现比 coalescing operator ??更容易阅读。

如果要测试条件,可以使用这个

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;