代码检查:“ContainsKey” 调用在将条目添加到字典之前是冗余的
此检查报告了一条 if 语句,它只是在检查 ContainsKey 后,在相同密钥和相同值的情况下,在 添加 和索引赋值之间进行选择。 在该模式下,存在性检查是冗余的,因为一次索引赋值已能处理两种情况。
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日