一:前言
如果只是判断字典中某个值是否存在,使用Contains和TryGetValue都可以。如果需要判断是否存在之后再得到某个值,尽量使用TryGetValue
if (Dictionary.TryGetValue(key, out value))
{
}
if(Dictionary.ContainsKey(key))
{
var value = Dictionary[key];
}
二:解释
先看一下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 again
// to ensure it didn't expire (otherwise, we open a ---- where TryGetValue misreports an
// expired key as a live key with a null value.)
if (primary != null)
{
value = (TValue)secondary;
return true;
}
}
value = default(TValue);
return false;
}
再看一下ContainsKey和字典索引的实现
public bool ContainsKey(TKey key) {
return FindEntry(key) >= 0;
}
public TValue this[TKey key] {
get {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set {
Insert(key, value, false);
}
}
想得到某个值,用TryGetValue只调用了1次FindEnty,而ContainKey判断还需要使用字典索引,一共需要调用2次FindEnty才能获取到值