首页 文章

转换可空的布尔?布尔

提问于
浏览
88

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

我试过 x.Valuex.HasValue ......

10 回答

  • 126

    你最终必须决定null bool代表什么 . 如果 null 应为 false ,则可以执行以下操作:

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

    要么:

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

    要么:

    bool newBool = x ?? false;
    
  • 2

    您可以使用null-coalescing operatorx ?? something ,其中 somethingxnull 时要使用的布尔值 .

    例:

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

    newBool 将是假的 .

  • 1

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

    bool? nullableBool = null;
    
     bool actualBool = nullableBool.GetValueOrDefault();
    
  • 4

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

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

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

  • 72

    如果您要在 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);
    
  • 91

    完整的方式是:

    bool b1;
    bool? b2 = ???;
    if (b2.HasValue)
       b1 = b2.Value;
    

    或者您可以使用测试特定值

    bool b3 = (b2 == true); // b2 is true, not false or null
    
  • 2
    bool? a = null;
    bool b = Convert.toBoolean(a);
    
  • 4

    就像是:

    if (bn.HasValue)
    {
      b = bn.Value
    }
    
  • 0

    这个答案适用于您只想在条件下测试 bool? 的用例 . 它也可以用来获得正常的 bool . 这是一个替代我个人发现比 coalescing operator ?? 更容易阅读 .

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

    bool? nullableBool = someFunction();
    if(nullableBool == true)
    {
        //Do stuff
    }
    

    只有当 bool? 为真时,上述if才会成立 .

    您也可以使用它从 bool? 分配常规 bool

    bool? nullableBool = someFunction();
    bool regularBool = nullableBool == true;
    

    女巫是一样的

    bool? nullableBool = someFunction();
    bool regularBool = nullableBool ?? false;
    
  • 2

    这是主题的有趣变化 . 在第一眼和第二眼,你会假设真正的分支被采取 . 不是这样!

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

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

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

相关问题