我应该使用'!IsGood`或`IsGood == FALSE`? [英] Should I use `!IsGood` or `IsGood == false`?
问题描述
我一直看到code,做检查,这样
I keep seeing code that does checks like this
if (IsGood == false)
{
DoSomething();
}
或本
if (IsGood == true)
{
DoSomething();
}
我讨厌这种语法,并始终使用下面的语法。
I hate this syntax, and always use the following syntax.
if (IsGood)
{
DoSomething();
}
或
if (!IsGood)
{
DoSomething();
}
是否有任何理由使用 ==真
或 ==虚假
'?
它是一个可读性的事情吗?难道人们只是不明白布尔变量?
Is it a readability thing? Do people just not understand Boolean variables?
此外,有没有两者之间的性能差异?
Also, is there any performance difference between the two?
推荐答案
我总是窃喜(或有人扔东西,这取决于我的心情),当我遇到
I always chuckle (or throw something at someone, depending on my mood) when I come across
if (someBoolean == true) { /* ... */ }
由于肯定,如果你不能依赖于你的比较会返回一个布尔值的事实,那么你可以不依赖于任何比较结果为真,所以code应该成为
because surely if you can't rely on the fact that your comparison returns a boolean, then you can't rely on comparing the result to true either, so the code should become
if ((someBoolean == true) == true) { /* ... */ }
不过,当然,这确实应该
but, of course, this should really be
if (((someBoolean == true) == true) == true) { /* ... */ }
不过,当然...
but, of course ...
(啊,编译失败。回去工作了。)
(ah, compilation failed. Back to work.)
这篇关于我应该使用'!IsGood`或`IsGood == FALSE`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!