DictionaryExtension.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace SuperSocket.Common
  6. {
  7. /// <summary>
  8. /// Extension class for IDictionary
  9. /// </summary>
  10. public static class DictionaryExtension
  11. {
  12. /// <summary>
  13. /// Gets the value by key.
  14. /// </summary>
  15. /// <typeparam name="T"></typeparam>
  16. /// <param name="dictionary">The dictionary.</param>
  17. /// <param name="key">The key.</param>
  18. /// <returns></returns>
  19. public static T GetValue<T>(this IDictionary<object, object> dictionary, object key)
  20. where T : new()
  21. {
  22. T defaultValue = default(T);
  23. return GetValue<T>(dictionary, key, defaultValue);
  24. }
  25. /// <summary>
  26. /// Gets the value by key and default value.
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="dictionary">The dictionary.</param>
  30. /// <param name="key">The key.</param>
  31. /// <param name="defaultValue">The default value.</param>
  32. /// <returns></returns>
  33. public static T GetValue<T>(this IDictionary<object, object> dictionary, object key, T defaultValue)
  34. {
  35. object valueObj;
  36. if (!dictionary.TryGetValue(key, out valueObj))
  37. {
  38. return defaultValue;
  39. }
  40. else
  41. {
  42. return (T)valueObj;
  43. }
  44. }
  45. }
  46. }