可为空的类型和 &&

本文关键字:amp 类型 | 更新日期: 2023-09-27 17:56:06

if语句中处理可为Null的布尔值的正确方法是什么?

1:

if ((complaint.ChargeSubcontractor ?? false) && x == y)

阿拉伯数字:

if (complaint.ChargeSubcontractor.Value && x == y)

3:

if ((complaint.ChargeSubcontractor != null && complaint.ChargeSubcontractor.Value) && x == y)

可为空的类型和 &&

为什么不呢

if (complaint.ChargeSubcontractor == true && x == y)

如果ChargeSubcontractor null,这将返回false

如果ChargeSubcontractor.HasValue为假(即如果ChargeSubcontractor为空),ChargeSubcontractor.Value将引发异常,因此不要使用#2。

示例 #1 和 #3 是等效的,但您可以使用ChargeSubcontractor == true来提高可读性。

我认为

不一定有规范的答案,但这是我的看法:

1:您可以将complaint.ChargeSubcontractor ?? false替换为complaint.ChargeSubcontractor.GetValueOrDefault(false)

2:在调用.Value之前,您需要检查complaint.ChargeSubcontractor是否确实具有值

3:见#1。

if (complaint.ChargeSubcontractor.HasValue && complaint.ChargeSubcontractor.Value && x == y)

为简洁起见,我将使

bool? z = complaint.ChargeSubcontractor;

如果z == null的情况未定义或应该抛出错误,我会选择:

if (z.Value && x == y)

如果z == null应该被视为z == false,我会执行以下操作。在大多数情况下,这是我推荐的。

if (z == true && x == y)

也有效且等同于上述内容,但IMO不那么清晰简洁:

if (z.GetValueOrDefault() && x == y)
if (z != null && z.Value && x == y)
if ((z ?? false) && x == y)

如果您正在寻找falsenull,而不仅仅是true,我的首选方法也非常有效。其他方法将要求您更大幅度地更改代码以更改匹配值。

if (z == true && x == y)
if (z == false && x == y)
if (z == null && x == y)