【问题标题】:c# What does this line mean?c#这条线是什么意思?
【发布时间】:2012-05-04 12:04:25
【问题描述】:

有人能解释一下下面的代码return total ?? decimal.Zero吗?

public decimal GetTotal()
{
    // Part Price * Count of parts sum all totals to get basket total
    decimal? total = (from basketItems in db.Baskets
                      where basketItems.BasketId == ShoppingBasketId
                      select (int?)basketItems.Qty * basketItems.Part.Price).Sum();
    return total ?? decimal.Zero;
}

是以下意思吗?

    if (total !=null) return total;
    else return 0;

【问题讨论】:

  • 所以基于大约 10 个响应,我猜它被称为“null-coalescing operator”然后??? :p

标签: c# return-value null-coalescing-operator


【解决方案1】:

是的,就是这个意思。它被称为null-coalescing operator

这只是一个语法快捷方式。但是,它可能更有效,因为正在读取的值只评估一次。 (请注意,在两次评估该值有副作用的情况下也可能存在功能差异。)

【讨论】:

  • 除此之外,具体的代码示例等同于return total.GetValueOrDefault(decimal.Zero) 或简单的return total.GetValueOrDefault(),因为无论如何十进制默认为零。
【解决方案2】:

C# 中的?? 称为null coalescing operator。它大致相当于下面的代码

if (total != null) {
  return total.Value;
} else {
  return Decimal.Zero;
}

上述if 语句扩展和?? 运算符之间的一个关键区别是如何处理副作用。在?? 示例中,获取值total 的副作用仅发生一次,但在if 语句中它们发生两次。

在这种情况下,这并不重要,因为total 是本地的,因此没有副作用。但如果说它是一个副作用属性或方法调用,这可能是一个因素。

// Here SomeOperation happens twice in the non-null case 
if (SomeOperation() != null) {
  return SomeOperation().Value;
} else { 
  return Decimal.Zero;
}

// vs. this where SomeOperation only happens once
return SomeOperation() ?? Decimal.Zero;

【讨论】:

  • 更准确地说,您可以在等效代码块中评估一次值,即tmp = SomeOperation(); if (tmp != null) { return tmp.Value; } else { return Decimal.Zero; }
【解决方案3】:

它是空合并运算符。

实际上,就像这样重写代码:

 return (total != null) ? total.Value : decimal.Zero;

【讨论】:

  • 不,这就像重写代码return (total != null) ? total.Value : decimal.Zero;
  • 我的错误,我没有注意到它是decimal?。我会更新答案。
【解决方案4】:

你成功了。它被称为空合并运算符。看看here

【讨论】:

    【解决方案5】:

    返回第一个非空表达式(第一个表达式为total,第二个表达式为decimal.Zero

    所以如果total 为空,decimal.Zero 将被返回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-19
      • 2020-01-22
      • 1970-01-01
      • 2012-03-23
      • 2010-11-02
      相关资源
      最近更新 更多