转换可空的布尔?布尔

Ken*_*hou 109 c# nullable

你如何将一个可空置换bool?boolC#?

我试过x.Value还是x.HasValue......

Ken*_*isa 171

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

bool newBool = x.HasValue ? x.Value : false;
Run Code Online (Sandbox Code Playgroud)

要么:

bool newBool = x.HasValue && x.Value;
Run Code Online (Sandbox Code Playgroud)

要么:

bool newBool = x ?? false;
Run Code Online (Sandbox Code Playgroud)


SLa*_*aks 101

您可以使用null-coalescing运算符:x ?? something,其中something是您想要使用的布尔值(如果x是)null.

例:

bool? myBool = null;
bool newBool = myBool ?? false;
Run Code Online (Sandbox Code Playgroud)

newBool 将是假的.

  • 所以,‘布尔?myBool = null; 布尔 newBool​​ = myBool ?? 假;` (2认同)

Joe*_*ggs 83

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

 bool? nullableBool = null;

 bool actualBool = nullableBool.GetValueOrDefault();
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是简洁和C#noob-friendlyness之间的最佳混合.另请注意,您可以指定默认值. (6认同)
  • 我喜欢使用这种方法,因为它可以创建'优雅'if语句`if(nullableBool.GetValueOrDefault())` (4认同)

Jar*_*Par 5

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

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

}
Run Code Online (Sandbox Code Playgroud)

??通过检查所提供的空的表达式可空值的作品。如果可为空的表达式具有一个值,则将使用它的值,否则它将使用位于??


Dav*_*Yaw 5

如果要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"; }
Run Code Online (Sandbox Code Playgroud)

当然,您也可以将其与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.
Run Code Online (Sandbox Code Playgroud)

如果要将其转换为布尔值以传递到应用程序的其他部分,则需要Null Coalesce运算符。

bool? b = ...;
bool b2 = b ?? true; // null becomes true
b2 = b ?? false; // null becomes false
Run Code Online (Sandbox Code Playgroud)

如果您已经检查过null,并且只需要该值,则访问Value属性。

bool? b = ...;
if(b == null)
    throw new ArgumentNullException();
else
    SomeFunc(b.Value);
Run Code Online (Sandbox Code Playgroud)


Rém*_*émi 5

这个答案适用于当您只想测试bool?某个条件时的用例。它也可以用来获得正常的bool. 我个人认为这是一种比coalescing operator ??.

如果你想测试一个条件,你可以使用这个

bool? nullableBool = someFunction();
if(nullableBool == true)
{
    //Do stuff
}
Run Code Online (Sandbox Code Playgroud)

仅当 the 为真时,上述 if 才为bool?真。

您还可以使用它来指定一个常规boolbool?

bool? nullableBool = someFunction();
bool regularBool = nullableBool == true;
Run Code Online (Sandbox Code Playgroud)

女巫是一样的

bool? nullableBool = someFunction();
bool regularBool = nullableBool ?? false;
Run Code Online (Sandbox Code Playgroud)