using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson.Serialization.Attributes;
namespace Model
{
///
/// 父子层级信息
///
public class ChildrenComponent: Component where T : Entity
{
[BsonIgnore]
public T Parent { get; private set; }
private readonly Dictionary idChildren = new Dictionary();
[BsonIgnore]
public int Count
{
get
{
return this.idChildren.Count;
}
}
public void Add(T child)
{
child.GetComponent>().Parent = (T) this.Owner;
this.idChildren.Add(child.Id, child);
}
public T Get(long id)
{
T child = null;
this.idChildren.TryGetValue(id, out child);
return child;
}
public T[] GetChildren()
{
return this.idChildren.Values.ToArray();
}
private void Remove(Entity entity)
{
this.idChildren.Remove(entity.Id);
entity.Dispose();
}
public void Remove(long id)
{
T child;
if (!this.idChildren.TryGetValue(id, out child))
{
return;
}
this.Remove(child);
}
public override void Dispose()
{
if (this.Id == 0)
{
return;
}
base.Dispose();
foreach (T child in this.idChildren.Values.ToArray())
{
child.Dispose();
}
this.Parent?.GetComponent>().Remove(this.Id);
}
}
public static class ChildrenHelper
{
public static void AddChild(this T parent, T child) where T : Entity
{
parent.GetComponent>().Add(child);
}
public static void RemoveChild(this T entity, long id) where T : Entity
{
entity.GetComponent>().Remove(id);
}
public static T GetChild(this T entity, long id) where T : Entity
{
return entity.GetComponent>().Get(id);
}
public static T[] GetChildren(this T entity) where T : Entity
{
return entity.GetComponent>().GetChildren();
}
}
}