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.
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)
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)
| 归档时间: |
|
| 查看次数: |
100411 次 |
| 最近记录: |