假设我需要增加Value
a 中的条目Dictionary
,例如:
public void Increment( string key, int increment )
{
m_dict[key] += increment;
}
并且还假设我需要在没有条目时使其工作key
,例如:
public void Increment( string key, int increment )
{
if ( m_dict.ContainsKey( key ) )
{
m_dict[key] += increment;
}
else
{
m_dict[key] = increment;
}
}
有没有办法将key
查找次数减少到一个?
我能想到的最好的解决方案是以下,这有点笨拙并且使用两个查找:
public void Increment( string key, int increment )
{
long value;
if ( m_dict.TryGetValue( key, out value ) )
{
m_dict[key] = value + increment;
}
else
{
m_dict.Add( key, increment );
}
}