CodeQL 文档

容器内容从未被访问

ID: cs/unused-collection
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - maintainability
   - useless-code
   - external/cwe/cwe-561
Query suites:
   - csharp-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

如果从未使用集合的内容,则该集合是无用的,因此也是不必要的。这会增加性能开销,使代码难以理解,并且可能表明逻辑错误。

建议

如果不再需要该集合,请将其删除,或者确保按预期使用它。

示例

在此示例中,属性 Names 返回了错误的集合 (genres)。此逻辑错误意味着 names 集合已填充但从未被访问。

class Composers
{
    IList<string> names, genres;

    public Composers()
    {
        names = new List<string> { "Bach", "Beethoven", "Chopin" };
        genres = new List<string> { "Classical", "Romantic", "Jazz" };
    }

    public IList<string> Names
    {
        get { return genres; }
    }

    public IList<string> Genres
    {
        get { return genres; }
    }
}

通过为 Names 返回正确的字段来修复代码。

class Composers
{
    IList<string> names, genres;

    public Composers()
    {
        names = new List<string> { "Bach", "Beethoven", "Chopin" };
        genres = new List<string> { "Classical", "Romantic", "Jazz" };
    }

    public IList<string> Names
    {
        get { return names; }
    }

    public IList<string> Genres
    {
        get { return genres; }
    }
}
  • ©2025GitHub 公司
  • 条款
  • 隐私