许多文章都推荐大家在C#的Dictionary中使用TryGetValue而不是先ContainsKey判断然后再取值,通过源码我们很容易理解:
这是TryGetValue的源码:
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
lock(_lock)
{
VerifyIntegrity();
return TryGetValueWorker(key, out value);
}
}
private bool TryGetValueWorker(TKey key, out TValue value)
{
int entryIndex = FindEntry(key);
if (entryIndex != -1)
{
Object primary = null;
Object secondary = null;
_entries[entryIndex].depHnd.GetPrimaryAndSecondary(out primary, out secondary);
// Now that we've secured a strong reference to the secondary, must check the primary aga