对于数字,它总是相同的漂亮:
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?
)值得使用这种语法时,我都很好奇总是:
if(b ?? false) { ... } // looks best to me
P.S.:这可能看起来像是基于意见的问题,但我没有找到类似的东西来单独清除我所有的疑虑......也许其中一些最适合在某些场景中使用,我想知道在哪些场景中.
最佳答案
语言设计者有两种选择,只要允许 bool?
参与需要 bool
的控制语句的控制表达式:
- 允许它,并在遇到
null
时做出任意决定治疗 - 不允许它,迫使您在每次相关时做出决定。
请注意,设计师对 if(a < 123)
的问题要少得多。语句,因为“否”是对“null
是否小于 123”、“null
是否大于 123”、“null
是否等于 123”等问题的有效答案。
if (b ?? false)
和 if (b ?? true)
是非常方便的结构,可以让您向代码的读者和编译器解释您希望以何种方式处理 null
s 存储在 bool?
中变量。
关于c# - bool ?比较 bool vs GetValueOrDefault vs ??运算符(operator),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736697/