首页 > 解决方案 > 'var' 在至少一个执行路径上为空 - sonarqube 还是?

问题描述

在使用 sonarqube 分析我的代码时,我遇到'variableProducerAgreements' is null on at least one execution path了以下代码(foreach 循环):

然而,在查看它并尝试各种事情时,variableProducerAgreements在这个 foreach 循环中似乎永远不会为空。在代码审查期间,我被告知它可以“完全”为空,应该添加条件逻辑来处理它。但我不明白它如何为空,因此不确定如何添加条件。有任何想法吗?

标签: c#foreachsonarqube

解决方案


我看不到variableProducerAgreements可能为 null 的方式,因为您在顶部放置了 null 防护(并假设您的属性 getter 中没有任何疯狂的代码)。

if (userProfile?.ProducerProfile == null)
    return result;

.NET 中的WhereandFindAll方法不返回 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 的风险。

此外,审阅者应该能够解释他/她的推理。


推荐阅读