想知道是否有更简单的方法来检查可空的bool是否为真.
我发现自己做了很多像这样的代码变得非常笨重.有没有更快的方法呢?
bool? x = false;
if (x.hasValue && x.Value) ...
Run Code Online (Sandbox Code Playgroud)
似乎必须有一个干净的更快的方法来检查真实
Joa*_*nvo 12
用途GetValueOrDefault:
if(x.GetValueOrDefault(false))
Run Code Online (Sandbox Code Playgroud)
您也可以将其与其他类型一起使用.
可能很多开发人员对此并不熟悉,但是可以使用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;
Run Code Online (Sandbox Code Playgroud)
并进行条件检查:-
if (nullableBool ?? false) { ... }
Run Code Online (Sandbox Code Playgroud)
另一个选项是GetValueOrDefault方法
if (nullableBool.GetValueOrDefault(false))
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1919 次 |
| 最近记录: |