对于数字,它总是相同的漂亮:
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
我很好奇是否在使用nullables(至少是bool?
)时,是否总是需要使用此语法:
if(b ?? false) { ... } // looks best to me
P.S.: 这可能看起来像基于个人意见的问题,但我无法独自解决所有疑惑......也许有些最好在特定场景中使用,我想知道哪些场景。
bool
为空,你希望发生什么?应该执行if
块,执行else
块还是两者都不执行?答案取决于这一点,而你的示例在这方面做了不同的事情。 - Heinzi