if() 语句中的可空布尔值 - 需要检查吗? [英] nullable bool in if() statement - checks required?

查看:87
本文介绍了if() 语句中的可空布尔值 - 需要检查吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在同事的代码中遇到了这个问题.他有一个可以为空的 bool 类型,他像这样比较:

I just came across this in a coworkers code. He has a nullable bool type that he compares like this:

//foo has no value here and evaluated to false
if(foo==true)
{
    doSomething();
}

通常,我检查可空布尔值的方式是这样的:

Typically, the way I check a nullable boolean is something like this:

bool IsTrue(bool? value)
{
   return value.HasValue && value.Value;
}

if(IsTrue(foo)){
   doSomething()
}

我使用了两种方法,它们的工作方式似乎相同.我在问哪种方法是正确的,是否需要额外的检查?

现在我在质疑我自己和我的同事的代码.我在这里做这个额外的检查有什么意义吗?或者我可以安全地做第一种方式吗?

Now I am questioning both myself and my coworkers code. Is there any point in me doing this extra check here? Or can I safely do it the first way?

谢谢(是的,我确实搜索过这个!:))

Thanks (and yes I did search for this! :))

推荐答案

实际上我不建议您将 null 视为 false.要么使用不可为空的布尔值,要么显式处理 null 值.另一种选择:

Actually I don't recommend you to treat null as false. Either use non-nullable boolean, or explicitly handle null value. One more option to do that:

if (foo ?? false)
{

}

这篇关于if() 语句中的可空布尔值 - 需要检查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆