c# - 'var' 在至少一个执行路径上为空 - sonarqube 还是?
问题描述
在使用 sonarqube 分析我的代码时,我遇到'variableProducerAgreements' is null on at least one execution path
了以下代码(foreach 循环):
然而,在查看它并尝试各种事情时,variableProducerAgreements
在这个 foreach 循环中似乎永远不会为空。在代码审查期间,我被告知它可以“完全”为空,应该添加条件逻辑来处理它。但我不明白它如何为空,因此不确定如何添加条件。有任何想法吗?
解决方案
我看不到variableProducerAgreements
可能为 null 的方式,因为您在顶部放置了 null 防护(并假设您的属性 getter 中没有任何疯狂的代码)。
if (userProfile?.ProducerProfile == null)
return result;
.NET 中的Where
andFindAll
方法不返回 null。
但是,每次访问时都使用空条件可能会使ProducerProfile
某些工具和人员感到困惑。如果它为空,您将提前返回,因此您应该删除它们:
if (IsActingAsDelegate && userProfile.ProducerProfile.IsInactiveProducer)
{
variableProducerAgreements = userProfile.ProducerProfile.ProducerAgreements.FindAll(ag => ag.IsActive && ag.IsVariableBranchContract);
}
else
{
variableProducerAgreements = userProfile.ProducerProfile.ActiveAgreements.Where(a => a.IsVariableContract);
}
NullReferenceException
如果有办法让它在 if 语句之前为 null,那么当您访问该IsInactiveProducer
属性时,您也会冒 a 的风险。
此外,审阅者应该能够解释他/她的推理。
推荐阅读
- python - Nonetype 对象不可调用 - 查询数据库时
- mysql - 在通过 CloudBuild 构建的 CloudRun 实例中无法访问具有 unix 套接字的 CloudSQL
- java - 在 Minecraft 插件中为假玩家创建玩家数据
- python - Colab 如何测量 RAM?
- javascript - 使用 JavaScript 激活(显示)'title' HTML 属性
- javascript - 单击外部下拉菜单并关闭下拉反应
- next.js - 当下拉值更改nextjs时如何更改api调用
- verilog - Verilog中的进位检测
- java - 我无法将“blurkit”库添加到我的 android studio 项目中
- python - 通过链接使用 Bootstrap 或在 Django 中的环境中安装(pip install django-bootstrap3)