我们经常使用Dictionary<T> 来做些操作,查询一个object,没有找到就Add它。代码像如样:
1: private static Dictionary<string,Employee> employees;
2: …3: public static Employee GetByName(string name) {
4: Employee employee;5: if (!employees.TryGetValue(name, out employee)) {
6: employee = new Employee(whatever);
7: employees.Add(name, employee); 8: }9: return employee;
10: }现在我们写个扩展方法:
/// <summary> /// Gets the or add. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TDictionaryValue">The type of the dictionary value.</typeparam> /// <typeparam name="TActualValue">The type of the actual value.</typeparam> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="newValue">The new value.</param> /// <returns>TActualValue</returns>public static TActualValue GetOrAdd<TKey, TDictionaryValue, TActualValue>(this IDictionary<TKey, TDictionaryValue> dictionary,
TKey key, Func<TActualValue> newValue) where TActualValue : TDictionaryValue { TDictionaryValue value;if (!dictionary.TryGetValue(key, out value))
{ value = newValue.Invoke(); dictionary.Add(key, value);}
return (TActualValue)value;
}
一个HelpMethod:
1: public static Employee GetByName(string name)
2: {3: return employees.GetOrAdd(name, () => new Employee(){Name=name});
4: }最后看Test,简化了:
1: [Test]2: public void TestDic()
3: {4: employees = new Dictionary<string, Employee>();
5: var emp=GetByName("Petter");
6: Assert.AreEqual("Petter", emp.Name);
7: Assert.IsInstanceOf(typeof(Employee), emp);
8: }Employee这个Class用于演示,您可以随意创建,或是其他Object。希望这篇Post对你有帮助.
Author: Petter Liu http://wintersun.cnblogs.com