LevelComponent.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. namespace Base
  5. {
  6. /// <summary>
  7. /// 父子层级信息
  8. /// </summary>
  9. public class LevelComponent<T> : Component<T> where T: Entity<T>
  10. {
  11. [BsonIgnore]
  12. public T Parent { get; private set; }
  13. private List<T> children;
  14. [BsonElement, BsonIgnoreIfNull]
  15. private Dictionary<long, T> idChildren;
  16. [BsonElement, BsonIgnoreIfNull]
  17. private Dictionary<string, T> nameChildren;
  18. [BsonIgnore]
  19. public int Count
  20. {
  21. get
  22. {
  23. return this.idChildren.Count;
  24. }
  25. }
  26. public void Add(T t)
  27. {
  28. t.GetComponent<LevelComponent<T>>().Parent = this.Owner;
  29. if (this.idChildren == null)
  30. {
  31. this.children = new List<T>();
  32. this.idChildren = new Dictionary<long, T>();
  33. this.nameChildren = new Dictionary<string, T>();
  34. }
  35. this.children.Add(t);
  36. this.idChildren.Add(t.Id, t);
  37. this.nameChildren.Add(t.Name, t);
  38. }
  39. public T[] GetChildren()
  40. {
  41. return this.children.ToArray();
  42. }
  43. private void Remove(T t)
  44. {
  45. this.idChildren.Remove(t.Id);
  46. this.nameChildren.Remove(t.Name);
  47. if (this.idChildren.Count == 0)
  48. {
  49. this.children = null;
  50. this.idChildren = null;
  51. this.nameChildren = null;
  52. }
  53. t.Dispose();
  54. }
  55. public void Remove(long id)
  56. {
  57. T t;
  58. if (!this.idChildren.TryGetValue(id, out t))
  59. {
  60. return;
  61. }
  62. this.Remove(t);
  63. }
  64. public void Remove(string name)
  65. {
  66. T t;
  67. if (!this.nameChildren.TryGetValue(name, out t))
  68. {
  69. return;
  70. }
  71. this.Remove(t);
  72. }
  73. public override void Dispose()
  74. {
  75. if (this.Id == 0)
  76. {
  77. return;
  78. }
  79. base.Dispose();
  80. foreach (T t in this.children)
  81. {
  82. t.Dispose();
  83. }
  84. this.Parent?.GetComponent<LevelComponent<T>>().Remove(this.Id);
  85. }
  86. }
  87. }