using System; using System.Collections.Generic; using System.ComponentModel; namespace JiShe.CollectBus.Common.Extensions { /// /// Extension methods for Dictionary. /// public static class DictionaryExtensions { /// /// This method is used to try to get a value in a dictionary if it does exists. /// /// Type of the value /// The collection object /// Key /// Value of the key (or default value if key not exists) /// True if key does exists in the dictionary internal static bool TryGetValue(this IDictionary dictionary, string key, out T value) { object valueObj; if (dictionary.TryGetValue(key, out valueObj) && valueObj is T) { value = (T)valueObj; return true; } value = default(T); return false; } /// /// Gets a value from the dictionary with given key. Returns default value if can not find. /// /// Dictionary to check and get /// Key to find the value /// Type of the key /// Type of the value /// Value if found, default if can not found. [Description("从字典中获取具有给定键的值,如果找不到,则返回默认值")] public static TValue GetOrDefault(this IDictionary dictionary, TKey key) { TValue obj; return dictionary.TryGetValue(key, out obj) ? obj : default(TValue); } /// /// Gets a value from the dictionary with given key. Add value if can not find. /// /// Dictionary to check and get /// Key to find the value /// A factory method used to create the value if not found in the dictionary /// Type of the key /// Type of the value /// Value if found, default if can not found. [Description("从字典中获取具有给定键的值,如果找不到,则添加")] public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func factory) { TValue obj; if (dictionary.TryGetValue(key, out obj)) { return obj; } return dictionary[key] = factory(key); } /// /// Gets a value from the dictionary with given key. Add value if can not find. /// /// Dictionary to check and get /// Key to find the value /// A factory method used to create the value if not found in the dictionary /// Type of the key /// Type of the value /// Value if found, default if can not found. public static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func factory) { return dictionary.GetOrAdd(key, k => factory()); } } }