[英]What is the fastest way to check for nullable bool being true in C#?
想知道是否有更简单的方法来检查可为空的布尔值是否为真。
我发现自己在做这样的代码很多,而这真的很庞大。 有更快的方法吗?
bool? x = false;
if (x.hasValue && x.Value) ...
似乎必须有一种干净的更快的方法来检查真实情况
使用GetValueOrDefault
:
if(x.GetValueOrDefault(false))
您也可以将其与其他类型一起使用。
if (x == true)
那应该工作并且最短
可能很多开发人员对此并不熟悉,但是可以使用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;
并进行条件检查:-
if (nullableBool ?? false) { ... }
另一个选项是GetValueOrDefault方法
if (nullableBool.GetValueOrDefault(false))
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.