Dib*_*Dib 6 c# null-coalescing-operator sonarqube
在 SonarQube 的分析过程中,我们看到了许多此警告的示例
更改此条件,使其不总是评估为“假”;一些后续代码永远不会执行。
所以发生这种情况的一个例子是 - 对于给定的代码......
if (components?.ContainsKey(machineType) ?? false)
{
return components[machineType];
}
throw new ArgumentException($"There is no available configuration for {machineType}!");
Run Code Online (Sandbox Code Playgroud)
……我们得到……
我们正在使用 C# null 合并来快捷地进行空检查,以便提供components是一个字典,不是null,并且components 确实包含由machineType我们指定的键,然后我们返回components字典中machineType键的值。
否则,如果 components为 null,或者如果 Dictionary不包含键,则表达式计算为false并且我们不进入块并返回值,而是抛出异常。
请有人解释为什么 SonarQube 抱怨这个。如果我们重写它以使用空检查和&&ing的“老式”冗长风格,那么 SonarQube 就是一个快乐的兔子。
仅仅是 SonarQube 不了解??操作符吗?
还是我们只是在这样的语句中滥用?.or??运算符?