ChildrenComponent.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 ChildrenComponent: Component
  10. {
  11. [BsonIgnore]
  12. public Entity Parent { get; private set; }
  13. private readonly Dictionary<long, Entity> idChildren = new Dictionary<long, Entity>();
  14. [BsonIgnore]
  15. public int Count
  16. {
  17. get
  18. {
  19. return this.idChildren.Count;
  20. }
  21. }
  22. public void Add(Entity entity)
  23. {
  24. entity.GetComponent<ChildrenComponent>().Parent = this.Owner;
  25. this.idChildren.Add(entity.Id, entity);
  26. }
  27. public Entity Get(long id)
  28. {
  29. Entity entity = null;
  30. this.idChildren.TryGetValue(id, out entity);
  31. return entity;
  32. }
  33. public Entity[] GetChildren()
  34. {
  35. return this.idChildren.Values.ToArray();
  36. }
  37. private void Remove(Entity entity)
  38. {
  39. this.idChildren.Remove(entity.Id);
  40. entity.Dispose();
  41. }
  42. public void Remove(long id)
  43. {
  44. Entity entity;
  45. if (!this.idChildren.TryGetValue(id, out entity))
  46. {
  47. return;
  48. }
  49. this.Remove(entity);
  50. }
  51. public override void Dispose()
  52. {
  53. if (this.Id == 0)
  54. {
  55. return;
  56. }
  57. base.Dispose();
  58. foreach (Entity entity in this.idChildren.Values.ToArray())
  59. {
  60. entity.Dispose();
  61. }
  62. this.Parent?.GetComponent<ChildrenComponent>().Remove(this.Id);
  63. }
  64. }
  65. public static partial class ChildrenHelper
  66. {
  67. public static void Add(this Entity entity, Entity child)
  68. {
  69. entity.GetComponent<ChildrenComponent>().Add(child);
  70. }
  71. public static void Remove(this Entity entity, long id)
  72. {
  73. entity.GetComponent<ChildrenComponent>().Remove(id);
  74. }
  75. }
  76. }