CodeQL 文档

对 GetHashCode() 的无用调用

ID: cs/useless-gethashcode-call
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - readability
   - useless-code
Query suites:
   - csharp-security-and-quality.qls

单击以在 CodeQL 存储库中查看查询

整数上的方法 GetHashCode() 只是返回整数的原始值。因此,此方法调用是多余的、低效的,并且会掩盖哈希函数的逻辑。几种内置类型都具有此行为,包括 intuintshortushortlongulongbytesbyte

建议

删除对 GetHashCode() 的调用,并检查哈希函数。

示例

以下哈希函数有两个问题。首先,对 GetHashCode() 的调用是多余的,其次,哈希函数生成过多的冲突。

public override int GetHashCode()
{
    return row.GetHashCode() ^ col.GetHashCode();
}

通过删除对 GetHashCode() 的冗余调用,并更改哈希函数以减少冲突,可以解决这些问题。

public override int GetHashCode()
{
    return unchecked(row * 16777619 + col);
}

参考

  • ©GitHub 公司
  • 条款
  • 隐私