65.9K
CodeProject 正在变化。 阅读更多。
Home

注意:空值合并运算符 (??) 在运算符优先级顺序中较低。

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (12投票s)

2014年2月4日

CPOL
viewsIcon

20584

也许写一篇提示文章能确保我以后不再犯同样的错误。

引言

我最喜欢的运算符之一是空值合并运算符,或者说 ?? 运算符。它与可空类型一起使用,当可空值为 null 时,会评估为一个非 null 值。例如:

背景

int? foo = null; 
int bar = foo ?? 7;
// bar == 7
它是以下代码的简写:
int? foo = null; 
int bar = foo == null ? 7 : foo;
// bar == 7

运算符优先级顺序

然而,重要的是要记住运算符优先级顺序

int? top = 60;
int? bottom = 180;
int height = bottom ?? 0 - top ?? 0;

// So height == 120?
不对。当你看到这段代码时,它似乎应该像这样评估:
int? top = 60;
int? bottom = 180;
int height = (bottom ?? 0) - (top ?? 0);

// height == 120
然而,实际上它的评估方式是:
int? top = 60;
int? bottom = 180;
int height = bottom ?? (0 - top ?? 0);

// height == 180

这导致我浪费了不止一次的调试时间。

© . All rights reserved.