LevelComponent.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. [BsonElement]
  14. private readonly List<T> children = new List<T>();
  15. private readonly Dictionary<long, T> idChildren = new Dictionary<long, T>();
  16. private readonly Dictionary<string, T> nameChildren = new Dictionary<string, T>();
  17. [BsonIgnore]
  18. public int Count
  19. {
  20. get
  21. {
  22. return this.idChildren.Count;
  23. }
  24. }
  25. public void Add(T t)
  26. {
  27. t.GetComponent<LevelComponent<T>>().Parent = this.Owner;
  28. this.children.Add(t);
  29. this.idChildren.Add(t.Id, t);
  30. this.nameChildren.Add(t.Name, t);
  31. }
  32. public T[] GetChildren()
  33. {
  34. return this.children.ToArray();
  35. }
  36. private void Remove(T t)
  37. {
  38. this.idChildren.Remove(t.Id);
  39. this.nameChildren.Remove(t.Name);
  40. t.Dispose();
  41. }
  42. public void Remove(long id)
  43. {
  44. T t;
  45. if (!this.idChildren.TryGetValue(id, out t))
  46. {
  47. return;
  48. }
  49. this.Remove(t);
  50. }
  51. public void Remove(string name)
  52. {
  53. T t;
  54. if (!this.nameChildren.TryGetValue(name, out t))
  55. {
  56. return;
  57. }
  58. this.Remove(t);
  59. }
  60. public override void Dispose()
  61. {
  62. if (this.Id == 0)
  63. {
  64. return;
  65. }
  66. base.Dispose();
  67. foreach (T t in this.children)
  68. {
  69. t.Dispose();
  70. }
  71. this.Parent?.GetComponent<LevelComponent<T>>().Remove(this.Id);
  72. }
  73. }
  74. public static class LevelHelper
  75. {
  76. public static void AddChild<T>(this Entity<T> entity, T t) where T : Entity<T>
  77. {
  78. entity.GetComponent<LevelComponent<T>>().Add(t);
  79. }
  80. public static void RemoveChild<T>(this Entity<T> entity, long id) where T : Entity<T>
  81. {
  82. entity.GetComponent<LevelComponent<T>>().Remove(id);
  83. }
  84. public static void RemoveChild<T>(this Entity<T> entity, string name) where T : Entity<T>
  85. {
  86. entity.GetComponent<LevelComponent<T>>().Remove(name);
  87. }
  88. }
  89. }