using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using MongoDB.Bson.Serialization.Attributes; namespace Common.Base { public abstract class Entity : Object, ISupportInitialize { [BsonElement] private HashSet Components { get; set; } private Dictionary ComponentDict { get; set; } protected Entity() { this.Components = new HashSet(); this.ComponentDict = new Dictionary(); } public void AddComponent() where T : Component, new() { if (this.ComponentDict.ContainsKey(typeof (T))) { throw new Exception( string.Format("AddComponent, component already exist, id: {0}, component: {1}", this.Id, typeof(T).Name)); } T t = new T { Owner = this }; this.Components.Add(t); this.ComponentDict.Add(typeof (T), t); } public void RemoveComponent() where T : Component { Component t; if (!this.ComponentDict.TryGetValue(typeof (T), out t)) { throw new Exception( string.Format("RemoveComponent, component not exist, id: {0}, component: {1}", this.Id, typeof(T).Name)); } this.Components.Remove(t); this.ComponentDict.Remove(typeof(T)); } public T GetComponent() where T : Component { Component t; if (!this.ComponentDict.TryGetValue(typeof (T), out t)) { throw new Exception( string.Format("GetComponent, component not exist, id: {0}, component: {1}", this.Id, typeof(T).Name)); } return (T) t; } public Component[] GetComponents() { return this.Components.ToArray(); } public virtual void BeginInit() { } public virtual void EndInit() { foreach (Component component in this.Components) { component.Owner = this; this.ComponentDict.Add(component.GetType(), component); } } } }