【问题标题】:How can I use the Nullable Operator with the Null Conditional operator?如何将 Nullable 运算符与 Null 条件运算符一起使用?
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 这是什么意思?顺便说一句,通常任何数字乘以 NULL 都会返回 NULL。例如,这就是普通 SQL 的工作方式。 NULL 通常意味着“我不知道值”。想象一下这个例子:我将 5 个苹果乘以 NULL $ 每个苹果。所以我不知道一个苹果的价格。结果是我不知道总成本,所以结果为NULL。
【解决方案2】:

试试这个:

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

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

【讨论】:

    【解决方案3】:

    我认为您误解了null 条件运算符的使用。 当其中一个步骤产生null时,它用于将ifs链短路到null

    像这样:

    userCompanyName = user?.Company?.Name;
    

    请注意,如果useruser.CompanynulluserCompanyName 将包含null。 在你的例子中total 不能接受null,所以更多的是关于使用 ??最重要的是:

    total = (myFavoriteNumber ?? 0) * 2;
    

    【讨论】:

      【解决方案4】:

      试试这个

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

      【讨论】:

        猜你喜欢
        • 2011-02-22
        • 2020-04-22
        • 2014-02-16
        • 2013-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-21
        • 1970-01-01
        相关资源
        最近更新 更多