c# - bool ?比较 bool vs GetValueOrDefault vs ??运算符(operator)

标签 c# nullable

对于数字,它总是相同的漂亮:

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/

相关文章:

c# - 通过 DataAdapter 删除行

c# - 如何从列表中的列表中检索不同值的列表

c# - 给字符串一个空值

c# - 在 IL 中使用 Initobj 操作码初始化可空类型

MySQL 问题 - 唯一键无法正常运行,还是我误解了?

sql - 使用可为空字段否定 SQL WHERE 条件

django-admin - 为什么 django admin 不接受 Nullable 外键?

c# - 如何为动态创建的按钮创建 onClick 事件处理程序

c# - 如何提取自定义 header 值?

javascript - CollapsiblePanelExtender 点击事件