【发布时间】:2016-06-28 11:39:28
【问题描述】:
老路
int? myFavoriteNumber = 42;
int total = 0;
if (myfavoriteNumber.HasValue)
total += myFavoriteNumber.Value *2;
新方法?
int? myFavoriteNumber = 42;
total += myFavoriteNumber?.Value *2; //fails
【问题讨论】:
-
int total = (myfavoriteNumber.HasValue) ? myFavoriteNumber.Value * 2 : 0;有什么问题?还是一行,比您建议的“新方式”更具可读性 -
@ShadowWizard 我假设他可能想多次使用此功能,因此使用 += 以便他可以保持运行总数?我只是猜测。我同意你的观点,我仍然喜欢你的评论。
-
@PrimeByDesign 我会选择
??,就像this 的答案一样。
标签: c# nullable null-conditional-operator null-propagation-operator