检查布尔值是否为真?

Pet*_*erg 20 c#

bool foo = true;

// Do this?
if (foo)
{
}

// Or this?
if (foo == true)
{
}
Run Code Online (Sandbox Code Playgroud)

我喜欢他们中的一个和另一个我的同事.结果是一样的,但是(更)正确的是什么?

Jon*_*eet 47

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

if (foo)
{
}
Run Code Online (Sandbox Code Playgroud)

事实上,我看到很多人批评明确的比较,我甚至可能在此之前就已经这样做了.我会说"短"风格是惯用的.

编辑:

请注意,这并不意味着代码行始终不正确.考虑:

bool? maybeFoo = GetSomeNullableBooleanValue();
if (maybeFoo == true)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

这将编译,但没有"== TRUE"不会,因为有一个从没有隐式转换bool?bool.

  • 同意.我唯一一次使用verbose(foo == true)是因为foo变量名显然不是布尔值,只是为了便于阅读. (3认同)
  • +1 为 `bool?` 评论。我一直在使用 `(maybeFoo.HasValue && MaybeFoo.Value)` 但 `maybeFoo == true` 更好。 (2认同)
  • @fredw:另一个选项是添加“默认”值:`if(maybeFoo ?? false)`或`if(maybeFoo ?? true)`。但我通常更喜欢`==`。 (2认同)

Joh*_*zen 27

It depends on your situation.

I would say, if your bool has a good name, then:

if (control.IsEnabled)  // Read "If control is enabled."
{
}
Run Code Online (Sandbox Code Playgroud)

would be preferred.

If, however, the variable has a not-so-obvious name, checking against true would be helpful in understanding the logic.

if (first == true)  // Read "If first is true."
{
}
Run Code Online (Sandbox Code Playgroud)

  • 如果名称不明显,也许应该重命名... (27认同)
  • +1可读性应指导答案 - 理想情况下,您可以重命名变量,以便可以使用前者. (12认同)

Mic*_*ins 13

如果你打算选择

if(foo == true)
Run Code Online (Sandbox Code Playgroud)

为什么不一路走下去呢

if(foo == true == true == true == true == true == true == true == true == true)
Run Code Online (Sandbox Code Playgroud)

这是一回事.

我不同意,如果它明确命名(即IsSomething:),那么它可以不与真实比较,但否则你应该.如果它在if语句中显然可以与true进行比较.

if(monday)
Run Code Online (Sandbox Code Playgroud)

就像描述一样

if(monday == true)
Run Code Online (Sandbox Code Playgroud)

我也不喜欢相同的标准:

if(!monday)
Run Code Online (Sandbox Code Playgroud)

而不是

if(monday == false)
Run Code Online (Sandbox Code Playgroud)