繁体   English   中英

如何将Nullable运算符与Null条件运算符一起使用?

[英]How can I use the Nullable Operator with the Null Conditional operator?

老路

int? myFavoriteNumber = 42;
int total = 0;
if (myfavoriteNumber.HasValue)
  total += myFavoriteNumber.Value *2;

新方法?

int? myFavoriteNumber = 42; 
total += myFavoriteNumber?.Value *2; //fails 

零传播算子? 如它所说,将传播空值。 在int?.Value的情况下,这是不可能的,因为Value的类型int不能为null(如果可能的话,操作将变为null * 2 ,这意味着什么?)。 因此,“老路”仍然是目前的做法。

试试这个:

int? myFavoriteNumber = 42; 
total += (myFavoriteNumber??0) *2; 

如果myFavoriteNumber为null,则表达式( myFavoriteNumber?? 0 )返回0。

我想你误解了使用null条件运算符。 它是用来短路IFS的链null ,当一个步骤产生null

像这样:

userCompanyName = user?.Company?.Name;

请注意, userCompanyName将包含null ,如果useruser.Companynull 在你的例子中, total不能接受null ,所以它更多的是关于使用?? 比什么都重要:

total = (myFavoriteNumber ?? 0) * 2;

试试这个

int? myFavoriteNumber = 42; 
total += (myFavoriteNumber.Value!=null)? myFavoriteNumber.Value*2 : 0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM