布尔?与bool vs GetValueOrDefault vs ??进行比较 算子

Sin*_*atr 5 c# nullable

对于数字,它总是一样漂亮

if(a < 123) { ... } // disregards if `b` is `int?` or `int`
Run Code Online (Sandbox Code Playgroud)

但是用bool?

bool? b = ...
if(b) { ... } // compiler error: can't convert bool? to bool.
Run Code Online (Sandbox Code Playgroud)

有以下选项:

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
Run Code Online (Sandbox Code Playgroud)

每当nullables(至少bool?)值得始终使用此语法时,我就是好奇主义者:

if(b ?? false) { ... } // looks best to me
Run Code Online (Sandbox Code Playgroud)

PS:这可能看起来像基于意见的问题,但我发现并没有类似的方法可以单独消除所有疑问...也许其中某些问题在某些情况下最好用,我想知道在哪些情况下。

das*_*ght 9

语言设计者有两种选择,只要允许bool?参与需要以下内容的控制语句的控制表达式bool

  • 允许它,并在null治疗时做出任意决定
  • 禁止这样做,迫使您在每次相关时做出决定。

请注意,设计人员对于if(a < 123)语句的问题要少得多,因为“否”是对“ null小于123”,“ null大于123”,“ null等于123”等问题的有效答案。

if (b ?? false)if (b ?? true)非常方便的结构,让您对您的代码的读者,并以何种方式,你要请客编译器解释null存储在A S bool?变量。


Dav*_*ine 5

每次我看到有人使用可为空的 boolean 时bool?,我都会问他们为什么。通常,答案是——“好吧,我不太确定”。它有效地创建了一个三态条件,在我看来这使代码更难阅读。null 是什么意思,如果它总是假的,那么为什么首先要让它可以为呢?

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

if (b ?? false)
Run Code Online (Sandbox Code Playgroud)

语法超过

if (b.GetValueOrDefault())
Run Code Online (Sandbox Code Playgroud)