zoukankan      html  css  js  c++  java
  • 使Dictionary泛型查询简单化

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

  • 相关阅读:
    #include <NOIP2009 Junior> 细胞分裂 ——using namespace wxl;
    【NOIP合并果子】uva 10954 add all【贪心】——yhx
    NOIP2010普及组T4 三国游戏——S.B.S.
    NOIP2010普及组T3 接水问题 ——S.B.S.
    NOIP2011提高组 聪明的质监员 -SilverN
    NOIP2010提高组 关押罪犯 -SilverN
    uva 1471 defence lines——yhx
    json2的基本用法
    获取对象的属性个数
    替换指定规则的字符串
  • 原文地址:https://www.cnblogs.com/wintersun/p/1556021.html
Copyright © 2011-2022 走看看