TopDictionary.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Top.Api
  4. {
  5. /// <summary>
  6. /// 符合TOP习惯的纯字符串字典结构。
  7. /// </summary>
  8. public class TopDictionary : Dictionary<string, string>
  9. {
  10. public TopDictionary() { }
  11. public TopDictionary(IDictionary<string, string> dictionary)
  12. : base(dictionary)
  13. { }
  14. /// <summary>
  15. /// 添加一个新的键值对。空键或者空值的键值对将会被忽略。
  16. /// </summary>
  17. /// <param name="key">键名称</param>
  18. /// <param name="value">键对应的值,目前支持:string, int, long, double, bool, DateTime类型</param>
  19. public void Add(string key, object value)
  20. {
  21. string strValue;
  22. if (value == null)
  23. {
  24. strValue = null;
  25. }
  26. else if (value is string)
  27. {
  28. strValue = (string)value;
  29. }
  30. else if (value is Nullable<DateTime>)
  31. {
  32. Nullable<DateTime> dateTime = value as Nullable<DateTime>;
  33. strValue = dateTime.Value.ToString(Constants.DATE_TIME_FORMAT);
  34. }
  35. else if (value is Nullable<int>)
  36. {
  37. strValue = (value as Nullable<int>).Value.ToString();
  38. }
  39. else if (value is Nullable<long>)
  40. {
  41. strValue = (value as Nullable<long>).Value.ToString();
  42. }
  43. else if (value is Nullable<double>)
  44. {
  45. strValue = (value as Nullable<double>).Value.ToString();
  46. }
  47. else if (value is Nullable<bool>)
  48. {
  49. strValue = (value as Nullable<bool>).Value.ToString().ToLower();
  50. }
  51. else
  52. {
  53. strValue = value.ToString();
  54. }
  55. this.Add(key, strValue);
  56. }
  57. public new void Add(string key, string value)
  58. {
  59. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
  60. {
  61. base[key] = value;
  62. }
  63. }
  64. public void AddAll(IDictionary<string, string> dict)
  65. {
  66. if (dict != null && dict.Count > 0)
  67. {
  68. IEnumerator<KeyValuePair<string, string>> kvps = dict.GetEnumerator();
  69. while (kvps.MoveNext())
  70. {
  71. KeyValuePair<string, string> kvp = kvps.Current;
  72. Add(kvp.Key, kvp.Value);
  73. }
  74. }
  75. }
  76. }
  77. }