代码检查:在将条目添加到字典之前,'ContainsKey' 调用是多余的
此检查会报告仅为在具有相同键和值的情况下选择 添加 或索引赋值而检查 ContainsKey 的 if 语句。 在这种模式下,存在性检查是多余的,因为单次索引赋值已能处理两种情况。
using System.Collections.Generic;
class C
{
void AddOrUpdate(Dictionary<int, int> map, int key, int value)
{
if (!map.ContainsKey(key))
{
map.Add(key, value);
}
else
{
map[key] = value;
}
}
}
using System.Collections.Generic;
class C
{
void AddOrUpdate(Dictionary<int, int> map, int key, int value)
{
map[key] = value;
}
}
此检查仅报告分配值相等且仅需安全评估一次的情况。
2026年 5月 8日