【发布时间】:2021-06-03 20:40:15
【问题描述】:
我正在尝试使用 SonarQube 优化代码
List<string> itemList = serviceObject.GetItems();
我尝试使用以下代码验证列表
if(itemList != null && itemList.Any()
{
//Some operations
}
执行上述代码时,我收到 Sonarqube 错误 删除此表达式,该表达式的计算结果始终为“true” 所以我将代码重构为
if(itemList == null || !itemList.Any())
return;
//Some Operations
执行上述代码时,我收到 Sonarqube 错误 删除此表达式,该表达式的计算结果始终为“false”
谁能告诉我这里出了什么问题?
【问题讨论】:
-
您是否尝试将
= serviceObject.GetItems()替换为= null,看看会发生什么。也许.GetItems()方法中的某些东西确保它不为空?但这似乎是一个奇怪的警告。 -
能否贴出完整的代码。
-
@JakobBuskSørensen 除非启用可空引用类型,在这种情况下
itemList不能为空。 -
您使用的是哪个 C# 版本?您是否通过在文件中添加
#nullable enable或在csproj文件中添加<Nullable>enable</Nullable>来启用可空引用类型? -
serviceObject.GetItems() 返回什么类型? .错误意味着 itemList 始终为空
标签: c# list optimization sonarqube