代码检查:字典项移除可以通过单个 'Remove' 方法简化
在 C# 中, 删除 方法在 Dictionary<T,T> 中如果未找到键不会抛出异常,而是直接返回 false。 这意味着您无需使用 TryGetValue 来检查键是否存在于字典中再尝试移除它。
int RemoveValue(Dictionary<int, int> d, int toRemove)
{
if (d.TryGetValue(toRemove, out var result))
{
d.Remove(toRemove);
return result;
}
return -1;
}
int RemoveValue(Dictionary<int, int> d, int toRemove)
{
if (d.Remove(toRemove, out var result))
{
return result;
}
return -1;
}
最后修改日期: 2025年 9月 27日