You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SonarQube提示条件恒为false:是误报还是C#代码存在缺陷?

分析SonarQube对这段C#代码的检测结果

SonarQube检测到以下代码中text.Length == 3所在的elseif代码块存在问题,提示“修改该条件使其不会始终计算为‘false’;部分后续代码从未执行”,下面我们来分析这是误报还是代码真的存在逻辑漏洞。

代码示例

public void SonarPleaseWhy(IList<string> texts)
{
    var chain = new List<string>();

    bool firstItemAdded = false;
    bool otherItemAdded = false;

    foreach (var text in texts)
    {
        if (!firstItemAdded && text.Length == 1)
        {
            chain.Add(text);
            firstItemAdded = true;
        }
        else if (firstItemAdded && text.Length == 2)
        {
            chain.Add(text);
            otherItemAdded = true;
        }
        else if (otherItemAdded && text.Length == 3)
        {
            Console.WriteLine(string.Join(',', chain));
            chain.Clear();
            firstItemAdded = false;
            otherItemAdded = false;
        }
        else
        {
            chain.Clear();
            firstItemAdded = false;
            otherItemAdded = false;
        }
    }
}

逻辑分析

我们梳理变量的状态流转和分支触发条件:

  • 初始状态:firstItemAdded和otherItemAdded均为false
  • 第一个分支:仅当firstItemAdded为false且当前text长度为1时触发,触发后firstItemAdded设为true,otherItemAdded仍为false
  • 第二个分支:仅当firstItemAdded为true且当前text长度为2时触发,触发后otherItemAdded设为true,此时firstItemAdded保持true
  • 第三个分支:需要otherItemAdded为true且当前text长度为3。当第二个分支触发后,进入下一次循环时,firstItemAdded仍为true,如果此时的text长度是3,第二个分支的条件(text.Length == 2)不满足,就会进入第三个分支的判断——此时otherItemAdded是true,text.Length == 3成立,代码块会正常执行,完成输出并重置状态变量

举个实际测试用例:如果传入texts = ["a", "bb", "ccc"],第三次循环时第三个分支会被触发,执行Console.WriteLine和状态重置逻辑,说明这段代码是可以走到第三个分支的。

结论

SonarQube的这次检测属于误报。静态分析工具在追踪多步状态流转时可能存在局限性,没有正确识别到otherItemAdded变为true后,后续循环能触发第三个分支的场景。

内容的提问来源于stack exchange,提问作者user5194329

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:31:29