DictionaryFormatter.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections.Generic;
  2. using System.Text;
  3. namespace IFramework.Serialization
  4. {
  5. public class DictionaryFormatter<K,V> : StringFormatter<Dictionary<K,V>>
  6. {
  7. const string keyChar = "k";
  8. const string valueChar = "v";
  9. Dictionary<K, V> dic = new Dictionary<K, V>();
  10. StringFormatter<K> k = StringConvert.GetFormatter(typeof(K)) as StringFormatter<K>;
  11. StringFormatter<V> v = StringConvert.GetFormatter(typeof(V)) as StringFormatter<V>;
  12. public override void ConvertToString(Dictionary<K, V> t, StringBuilder builder)
  13. {
  14. if (t == null || t.Count == 0) return;
  15. builder.Append(StringConvert.midLeftBound);
  16. int count = 0;
  17. foreach (var item in t)
  18. {
  19. var _key = item.Key;
  20. var _value = item.Value;
  21. count++;
  22. builder.Append(StringConvert.leftBound);
  23. builder.Append(keyChar);
  24. builder.Append(StringConvert.colon);
  25. k.ConvertToString(_key, builder);
  26. builder.Append(StringConvert.dot);
  27. builder.Append(valueChar);
  28. builder.Append(StringConvert.colon);
  29. v.ConvertToString(_value, builder);
  30. builder.Append(StringConvert.rightBound);
  31. if (count != t.Count)
  32. {
  33. builder.Append(StringConvert.dot.ToString());
  34. }
  35. }
  36. builder.Append(StringConvert.midRightBound);
  37. }
  38. private void Read(string self, Dictionary<K, V> result)
  39. {
  40. K lastKey = default(K);
  41. ObjectFormatter<K>.ReadObject(self, (fieldName, inner) =>
  42. {
  43. if (fieldName == keyChar)
  44. {
  45. k.TryConvert(inner, out lastKey);
  46. }
  47. else if (fieldName == valueChar)
  48. {
  49. V value;
  50. if (v.TryConvert(inner, out value))
  51. {
  52. result.Add(lastKey, value);
  53. }
  54. else
  55. {
  56. result.Add(lastKey, default(V));
  57. }
  58. }
  59. });
  60. }
  61. public override bool TryConvert(string self, out Dictionary<K, V> result)
  62. {
  63. dic.Clear();
  64. bool bo = ListFormatter<K>.ReadArray(self, (inner) =>
  65. {
  66. if (inner.EndsWith(StringConvert.dot.ToString()))
  67. {
  68. inner = inner.Remove(inner.Length - 1, 1);
  69. }
  70. Read(inner, dic);
  71. });
  72. if (bo)
  73. {
  74. result = new Dictionary<K, V>(dic);
  75. }
  76. else
  77. {
  78. result = MakeDefault();
  79. }
  80. return bo;
  81. }
  82. }
  83. }