选择的答案是正确的。这是为 user2535489 提供正确的方法来实现他的想法:
public static class DictionaryExtensions
{
public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue fallback = default(TValue))
{
TValue result;
return dictionary.TryGetValue(key, out result) ? result : fallback;
}
}
然后可以使用:
Dictionary<string, int> aDictionary;
// Imagine this is not empty
var value = aDictionary.GetValue("TheKey"); // Returns 0 if the key isn't present
var valueFallback = aDictionary.GetValue("TheKey", 10); // Returns 10 if the key isn't present