检查布尔值是否正确? [英] Check if boolean is true?

查看:52
本文介绍了检查布尔值是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool foo = true;

// Do this?
if (foo)
{
}

// Or this?
if (foo == true)
{
}

我喜欢其中一个,而我的同事则另一个。结果是一样的,但是什么是(更多)正确的呢?

I like one of them and my coworker the other. The result is the same, but what is (more) correct?

推荐答案

我见过的表达意见的几乎每个人都喜欢

Almost everyone I've seen expressing an opinion prefers

if (foo)
{
}

的确,我看到很多人批评这种显式比较,甚至我自己以前也这样做。我会说短样式是惯用的。

Indeed, I've seen many people criticize the explicit comparison, and I may even have done so myself before now. I'd say the "short" style is idiomatic.

编辑:

请注意,这不是意味着代码行总是不正确。考虑:

Note that this doesn't mean that line of code is always incorrect. Consider:

bool? maybeFoo = GetSomeNullableBooleanValue();
if (maybeFoo == true)
{
    ...
}

可以编译,但是没有 == true的话就不会编译,因为没有从 bool?到<$ c $的隐式转换。 c> bool 。

That will compile, but without the "== true" it won't, as there's no implicit conversion from bool? to bool.

这篇关于检查布尔值是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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