可空类型和&&

时间:2014-04-02 14:20:45

标签: c# .net

在if语句中处理Nullable布尔值的正确方法是什么?

1:

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

2:

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

3:

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

5 个答案:

答案 0 :(得分:3)

为什么不

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

如果falseChargeSubcontractor

,则会返回null

答案 1 :(得分:1)

如果ChargeSubcontractor.Value为假(如果ChargeSubcontractor.HasValue为空),

ChargeSubcontractor将抛出异常,因此请勿使用#2。

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

答案 2 :(得分:1)

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

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

2:在调用complaint.ChargeSubcontractor

之前,您需要检查.Value是否确实有值

3:见#1。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

为简洁起见,我将

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)