TryGetValue已经为字典指定了类型的默认值,因此您可以使用:
dictionary.TryGetValue(key, out value);
并忽略返回值。然而,真正 将
刚刚返回
default(TValue),而不是一些自定义的默认值(也没有,更有效,执行委托的结果)。框架中没有比它更强大的功能了。我建议两种扩展方法:
public static TValue GetValueOrDefault<TKey, TValue> (this IDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue){ TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue;}public static TValue GetValueOrDefault<TKey, TValue> (this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> defaultValueProvider){ TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValueProvider();}(当然,您可能需要检查参数:)


![如果键不存在,则字典返回默认值[重复] 如果键不存在,则字典返回默认值[重复]](http://www.mshxw.com/aiimages/31/568461.png)
