简体   繁体   English

在C#中检查可空布尔是否正确的最快方法是什么?

[英]What is the fastest way to check for nullable bool being true in C#?

Wondering if there is a simpler way to check for a nullable bool being true. 想知道是否有更简单的方法来检查可为空的布尔值是否为真。

I find myself doing code like this a lot which gets real bulky. 我发现自己在做这样的代码很多,而这真的很庞大。 Any faster way to do it? 有更快的方法吗?

bool? x = false;
if (x.hasValue && x.Value) ...

Seems like there must be a clean faster way to check for true 似乎必须有一种干净的更快的方法来检查真实情况

Use GetValueOrDefault : 使用GetValueOrDefault

if(x.GetValueOrDefault(false))

You can also use this with other types. 您也可以将其与其他类型一起使用。

if (x == true)

那应该工作并且最短

May be many developers are not familiar with this but you can use the null coalesce operator (??) , as shown below: 可能很多开发人员对此并不熟悉,但是可以使用null合并运算符(??) ,如下所示:

    int? x = null;

    // Set y to the value of x if x is NOT null; otherwise, 
    // if x = null, set y to -1. 
    int y = x ?? -1;

and for condition check :- 并进行条件检查:-

if (nullableBool ?? false) { ... }

and another option is GetValueOrDefault Method 另一个选项是GetValueOrDefault方法

if (nullableBool.GetValueOrDefault(false)) 
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM