CodeQL 文档

取消引用变量始终为 null

ID: cs/dereferenced-value-is-always-null
Kind: problem
Security severity: 
Severity: error
Precision: very-high
Tags:
   - reliability
   - correctness
   - exceptions
   - external/cwe/cwe-476
Query suites:
   - csharp-security-and-quality.qls

点击以在 CodeQL 代码库中查看查询

如果取消引用变量(例如,作为方法调用中的限定符),并且该变量在导致取消引用的所有可能执行路径上都具有 null 值,则取消引用操作保证会导致 NullReferenceException

建议

确保在取消引用变量时,该变量不具有 null 值。

示例

在以下示例中,仅当 snull 时,才会执行条件 s.Length > 0

using System;

namespace NullAlways
{
    class Bad
    {
        void DoPrint(string s)
        {
            if (s != null || s.Length > 0)
                Console.WriteLine(s);
        }
    }
}

在修改后的示例中,通过使用 && 而不是 || 正确地保护了条件。

using System;

namespace NullAlways
{
    class Good
    {
        void DoPrint(string s)
        {
            if (s != null && s.Length > 0)
                Console.WriteLine(s);
        }
    }
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私