布尔?比较 bool vs GetValueOrDefault vs ??操作员

bool? compare with bool vs GetValueOrDefault vs ?? operator

数字总是一样的漂亮:

if(a < 123) { ... } // disregards if `b` is `int?` or `int`

但是 bool?:

bool? b = ...
if(b) { ... } // compiler error: can't convert bool? to bool.

有以下选项:

if(b == false) { ... } // looks ugly, comparing bool? with bool
if(b.GetValueOrDefault()) { ... } // unclear when condition is true (one must know it's `false`)
if(b.GetValueOrDefault(true)) { ... } // required few seconds to understand inversion

每当可空值(至少 bool?)值得使用这种语法时,我都很好奇 always:

if(b ?? false) { ... } // looks best to me

P.S.: 这可能看起来像是基于意见的问题,但我没有找到类似的东西来单独清除我所有的疑虑......也许其中一些最适合在某些情况下使用,我'我想知道是哪一个。

语言设计者有两种选择,允许 bool? 参与需要 bool:

的控制语句的控制表达式
  • 允许,null治疗时随意决定
  • 禁止它,迫使您在每次相关时做出决定。

请注意,设计者对 if(a < 123) 语句的问题要少得多,因为 "no" 是问题 "is null less than 123"、"is null greater than 123"、[=36 的有效答案=],等等。

if (b ?? false)if (b ?? true) 是非常方便的结构,可以让您向代码的读者和编译器解释您希望以何种方式处理存储的 nullbool? 变量中。

每次我看到有人使用可为 null 的布尔值 bool?,我都会问他们为什么。通常,答案是——"well, I'm not really sure"。它有效地创建了一个三态条件,在我看来,这无论如何都会使代码更难阅读。 null 是什么意思,如果它始终为 false 那么为什么要首先将其设置为 nullable

但是为了更直接地回答你的问题,我更喜欢

if (b ?? false)

语法优于

if (b.GetValueOrDefault())

几年后,根据个人经验,我可以看出以下语法显然是赢家:

if(b == false) { /* do something if false */ }
if(b == true) { /* do something if true */ }
if(b != false) { /* do something if NOT false, means true or null */ }
if(b != true) { /* do something if NOT true, means false or null */ }

我认为“丑陋”的东西原来是最容易理解的。

== 对比 ??

可空值通常是 linq 查询的结果,使用 ?? 添加不必要的复杂层来理解条件。

比较

if(Items?.Any(o => o.IsSelected) == true)

if(Items?.Any(o => o.IsSelected) ?? false)

第一个更容易阅读,它是一个简单的检查是否选择了任何项目。

当我(可能是未经训练的?)读到后者时,我必须在 ?? 处做一个心理句号,进行反转,然后我才明白什么时候会执行 if 块。使用 ?? 如果有足够的时间,我在快速浏览别人编写的代码甚至我自己的代码时很可能会犯错误。