C# ??运算符差异
C# ?? operator difference
'?? true' 和 if 语句中的 '== true'?
bool? b = Jsonfile.GetBoolean("testval");
if (b ?? true) { }
if (b == true) { }
是的。
如果 b
为空:
b == true
会 return 错误。
b ?? true
为真。
由于 ??
是 null-coalescing 运算符,它仅在左侧值为 null
时有效。在这种情况下,它确实很重要。
正如 juharr 对您的问题的评论:
b ?? false
is the same as b == true
这是真的,因为 b.GetValueOrDefault()
returns false
,在这种情况下实际上与 ?? false
相同。如果 b == null
,b.GetValueOrDefault() == true
将产生 false
。
是的,有。
当 b
为 null
或 true
时,b ?? true
将匹配
当 b
不是 null
并且是 true
时,b == true
将匹配
区别在于table的第一行(当b
为null
时)
b b ?? true b == true
==== ========== ==========
null true false
true true true
false false false
MSDN:
The ??
operator returns the left-hand operand if it is not null
, else, it returns the right-hand operand.
'?? true' 和 if 语句中的 '== true'?
bool? b = Jsonfile.GetBoolean("testval");
if (b ?? true) { }
if (b == true) { }
是的。
如果 b
为空:
b == true
会 return 错误。b ?? true
为真。
由于 ??
是 null-coalescing 运算符,它仅在左侧值为 null
时有效。在这种情况下,它确实很重要。
正如 juharr 对您的问题的评论:
b ?? false
is the same asb == true
这是真的,因为 b.GetValueOrDefault()
returns false
,在这种情况下实际上与 ?? false
相同。如果 b == null
,b.GetValueOrDefault() == true
将产生 false
。
是的,有。
当b
为 null
或 true
时,b ?? true
将匹配
当 b
不是 null
并且是 true
b == true
将匹配
区别在于table的第一行(当b
为null
时)
b b ?? true b == true
==== ========== ==========
null true false
true true true
false false false
MSDN:
The
??
operator returns the left-hand operand if it is notnull
, else, it returns the right-hand operand.