MarshalContextBasic.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Collections.Generic;
  2. namespace TBL.CSharp.Serialization.Marshal.Context
  3. {
  4. /// <summary>
  5. /// Marshal 风格的序列化上下文基础实现
  6. /// </summary>
  7. public class MarshalContextBasic : IMarshalContext
  8. {
  9. /// <summary>
  10. /// 已链接的符号
  11. /// </summary>
  12. private readonly IDictionary<int, string> _linkedSymbols =
  13. new Dictionary<int, string>();
  14. /// <summary>
  15. /// 已链接的对象
  16. /// </summary>
  17. private readonly IDictionary<int, object> _linkedObjects =
  18. new Dictionary<int, object>();
  19. /// <summary>
  20. /// 已链接的符号 Id
  21. /// </summary>
  22. private readonly IDictionary<string, int> _linkedSymbolIds =
  23. new Dictionary<string, int>();
  24. /// <summary>
  25. /// 已链接的对象 Id
  26. /// </summary>
  27. private readonly IDictionary<object, int> _linkedObjectIds =
  28. new Dictionary<object, int>();
  29. public void Clear()
  30. {
  31. _linkedSymbols.Clear();
  32. _linkedSymbolIds.Clear();
  33. _linkedObjects.Clear();
  34. }
  35. public string GetLinkableSymbol(int index) => _linkedSymbols[index];
  36. public string AddLinkableSymbol(string symbol)
  37. {
  38. var id = _linkedSymbols.Count + 1;
  39. _linkedSymbols.Add(id, symbol);
  40. _linkedSymbolIds.Add(symbol, id);
  41. return symbol;
  42. }
  43. public bool FindLinkableSymbol(string symbol, out int index) =>
  44. _linkedSymbolIds.TryGetValue(symbol, out index);
  45. public object GetLinkableObject(int index) => _linkedObjects[index];
  46. public T AddLinkableObject<T>(T element)
  47. {
  48. var id = _linkedObjects.Count + 1;
  49. _linkedObjects.Add(id, element);
  50. _linkedObjectIds.Add(element, id);
  51. return element;
  52. }
  53. public bool FindLinkableObject(object element, out int index) =>
  54. _linkedObjectIds.TryGetValue(element, out index);
  55. }
  56. }