c# - 混淆 if(something){} 和 if(something == true){}

标签 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/

相关文章:

c - if 语句有任何一个飞机输出吗?

C# 更改系统语言环境

c# - 使用自定义 FluentValidator 验证器验证枚举

c# - Google Analytics Reporting、GoogleAnalyticsSDK 和 winforms 应用

r - 如何在 R 中使用 ifelse 条件从向量中删除

c - C 中的 If 语句输出无效

c# - 带参数的 Dispatcher.BeginInvoke 操作

c# - 如何等待元素加载到 selenium webdriver 中?

Android 不会执行我的 else 语句

r - 每列采样一行,大量缺失数据