<分区>
我有时在 youtube 上看到有人写
if(something) { ...; }
代替
if(something == true) { ...; }
像这样使用 if 语句的规则是什么?是因为 if 语句默认检查某事是否为真?
标签 c# if-statement
<分区>
我有时在 youtube 上看到有人写
if(something) { ...; }
代替
if(something == true) { ...; }
像这样使用 if 语句的规则是什么?是因为 if 语句默认检查某事是否为真?
最佳答案
只是为了检查括号之间的条件是真还是假。
if(something == true) {}
在大多数情况下是一样的,请阅读下面为什么我使用most
这个词。
if(something) {}
我个人认为添加 == true
不会使其更具可读性。所以我倾向于使用if(something)
。我会选择您的团队使用的那个。一个人编程?选择您最喜欢的一个。
作为补充:当检查条件是否为假时,您可以使用:
if(!something) {}
注意:
来自 die maus 的回答:
While Max answer is correct, i would like to add something. While if (booleanVariable == true) and if (booleanVariable) are generally the exact same thing, you are not taking into consideration Nullable or bool? for shorthand.
关于c# - 混淆 if(something){} 和 if(something == true){},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187120/