posts - 930,  comments - 588,  views - 402万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

我们经常使用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

posted on   PetterLiu  阅读(910)  评论(0编辑  收藏  举报
编辑推荐:
· [.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)
点击右上角即可分享
微信分享提示