null合并操作顺序

Bra*_*itz 4 .net c# null null-coalescing-operator

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

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

当我将null传递给StartDepth时,合并失败,因为正在评估"Depth - StartDepth",首先将StartDepth转换为默认值0(降级?),而不是首先查看它是否为null并替换为Globals.相反,StartDepth.

这是一件众所周知的事吗?我能够通过添加括号来完成这项工作,但我真的不希望事情以这种方式工作.

Jon*_*eet 8

不,这不是一个错误.它是指定的优先顺序 - 二元-运算符的优先级高于??,因此您的代码是有效的:

return ((Depth - StartDepth) ?? Globals.StartDepth) * 
          PrintScale ?? Constants.YPixelsPerUnit;
Run Code Online (Sandbox Code Playgroud)

如果您不想要该优先级,则应明确指定它:

return (Depth - (StartDepth ?? Globals.StartDepth)) * 
          PrintScale ?? Constants.YPixelsPerUnit;
Run Code Online (Sandbox Code Playgroud)

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

double actualStartDepth = StartDepth ?? Globals.StartDepth;
double actualScale = PrintScale ?? Constants.YPixelsPerUnit;
return (depth - actualStartDepth) * actualScale;
Run Code Online (Sandbox Code Playgroud)