c#这条线是什么意思?

Gra*_*avy 3 c# return-value null-coalescing-operator

有人可以解释下面的代码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;
}
Run Code Online (Sandbox Code Playgroud)

这是否意味着以下?

    if (total !=null) return total;
    else return 0;
Run Code Online (Sandbox Code Playgroud)

Jon*_*ood 13

是的,这就是它的含义.它被称为null-coalescing运算符.

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

  • 除此之外,具体的代码示例等同于`return total.GetValueOrDefault(decimal.Zero)`或者只是`return total.GetValueOrDefault()`因为十进制默认为零. (2认同)

Jar*_*Par 6

??C#中被称为空合并运算符.它大致相当于以下代码

if (total != null) {
  return total.Value;
} else {
  return Decimal.Zero;
}
Run Code Online (Sandbox Code Playgroud)

上述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;
Run Code Online (Sandbox Code Playgroud)