using System.Collections.Generic; using System.Linq; using MongoDB.Bson.Serialization.Attributes; namespace Base { /// /// 父子层级信息 /// public class LevelComponent : Component where T: Entity { [BsonIgnore] public T Parent { get; private set; } [BsonElement] private readonly List children = new List(); private readonly Dictionary idChildren = new Dictionary(); private readonly Dictionary nameChildren = new Dictionary(); [BsonIgnore] public int Count { get { return this.idChildren.Count; } } public void Add(T t) { t.GetComponent>().Parent = this.Owner; this.children.Add(t); this.idChildren.Add(t.Id, t); this.nameChildren.Add(t.Name, t); } public T[] GetChildren() { return this.children.ToArray(); } private void Remove(T t) { this.idChildren.Remove(t.Id); this.nameChildren.Remove(t.Name); t.Dispose(); } public void Remove(long id) { T t; if (!this.idChildren.TryGetValue(id, out t)) { return; } this.Remove(t); } public void Remove(string name) { T t; if (!this.nameChildren.TryGetValue(name, out t)) { return; } this.Remove(t); } public override void Dispose() { if (this.Id == 0) { return; } base.Dispose(); foreach (T t in this.children) { t.Dispose(); } this.Parent?.GetComponent>().Remove(this.Id); } } public static class LevelHelper { public static void AddChild(this Entity entity, T t) where T : Entity { entity.GetComponent>().Add(t); } public static void RemoveChild(this Entity entity, long id) where T : Entity { entity.GetComponent>().Remove(id); } public static void RemoveChild(this Entity entity, string name) where T : Entity { entity.GetComponent>().Remove(name); } } }