ChildrenComponent.cs 1.6 KB

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