我们经常使用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
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)