删除SonarQube中不必要的布尔文字问题 – C#

huangapple go评论64阅读模式
英文:

Remove the unnecessary Boolean literal(s) issue in SonarQube - C#

问题

SonarQube对我的C#(v10)控制器类中的以下两个三元表达式抛出错误,错误信息是Remove the unnecessary Boolean literal(s).

IsSuccess = response == null ? false : true;
ResponseMessage = resp == true ? "Success" : "Failure",

我了解Null-合并/Null-合并-赋值运算符可以像这样使用:

variable ??= expression;

这是以下代码的缩写形式:

if (variable is null)
{
    variable = expression;
}

我可以在我的三元表达式中使用相同的方法吗?

英文:

SonarQube is throwing an error for the following 2 ternary expressions in my C#(v10) controller class citing Remove the unnecessary Boolean literal(s).:

IsSuccess = response == null ? false : true;
ResponseMessage = resp == true ? "Success" : "Failure",

I understand that Null-Coalescing / Null-Coalescing-Assignment operator can be used like:

variable ??= expression;

which is a shorthand for:

if (variable is null)
{
    variable = expression;
}

Can I make use of the same in my ternary expressions also?

答案1

得分: 4

我认为你遇到这个问题是因为你可以将它重写为

IsSuccess = response != null;

对于第二个表达式,你可以将它重写为

ResponseMessage = resp ? "Success" : "Failure";

三元运算符只需要在?的左边期望一个布尔值,所以如果值已经是布尔型,你无需再进行测试。

英文:

I think you are getting this issue as you can rewrite

IsSuccess = response == null ? false : true;

As

IsSuccess = response != null;

For the second expression you can rewite

ResponseMessage = resp == true ? "Success" : "Failure";

As

ResponseMessage = resp ? "Success" : "Failure";

The ternary operator is just expecting a bool on the lefthand side of the '?' as such if the value is already a bool you have no need to test it.

huangapple
  • 本文由 发表于 2023年3月3日 18:56:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定