c# - 空合并操作顺序

标签 c# .net null null-coalescing-operator

我从这个方法中得到了奇怪的结果:

public static double YFromDepth(double Depth, double? StartDepth, double? PrintScale)
{               
    return (Depth - StartDepth ?? Globals.StartDepth) * PrintScale ?? Constants.YPixelsPerUnit ;
}

当我将 null 传递给 StartDepth 时,合并失败,因为“Depth - StartDepth”的评估似乎是首先将 StartDepth 转换为默认值 0(降级?),而不是首先查看它是否为 null 并代入取而代之的是 Globals.StartDepth。

这是众所周知的事情吗?我能够通过添加括号来完成这项工作,但我真的没想到会这样。

最佳答案

不,这不是错误。这是 specified order of precedence - 二进制 - 运算符的优先级高于 ??,因此您的代码实际上是:

return ((Depth - StartDepth) ?? Globals.StartDepth) * 
          PrintScale ?? Constants.YPixelsPerUnit;

如果你不想要那个优先级,你应该明确指定它:

return (Depth - (StartDepth ?? Globals.StartDepth)) * 
          PrintScale ?? Constants.YPixelsPerUnit;

我个人会扩展该方法以使其更清晰:

double actualStartDepth = StartDepth ?? Globals.StartDepth;
double actualScale = PrintScale ?? Constants.YPixelsPerUnit;
return (depth - actualStartDepth) * actualScale;

关于c# - 空合并操作顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266811/

相关文章:

C# ASP.NET 应用程序正则表达式

c# - Active Directory 密码到期日期

c# - 当 Array.BinarySearch 说一个带有负索引的数组时,它是什么意思?

c# - 方法重载中的 Expression<Func<T,bool>> 与 Func<T,bool>

ruby-on-rails - Ruby on Rails : Is there a way to make blank form inputs submit nil?

c - 下面的c代码会产生内存泄漏吗?

c# - 我可以将 MVC 2 DataAnnotation 属性添加到现有属性吗?

c# - 将字符串转换为 int 然后乘以另一个 int

c# - 继承 .net 类

C# 空传播运算符/条件访问表达式和 if block