using System; using System.Collections.Generic; using System.Linq; using Common.Helper; using MongoDB.Bson.Serialization.Attributes; namespace Common.Base { public abstract class Entity: Object where T : Entity { [BsonElement, BsonIgnoreIfNull] private HashSet> components; private Dictionary> componentDict = new Dictionary>(); public T Clone() { return MongoHelper.FromBson(MongoHelper.ToBson(this)); } public K AddComponent() where K : Component, new() { K component = (K) Activator.CreateInstance(typeof (K)); component.Owner = (T) this; if (this.componentDict.ContainsKey(component.GetComponentType())) { throw new Exception( string.Format("AddComponent, component already exist, id: {0}, component: {1}", this.Id, typeof (K).Name)); } if (this.components == null) { this.components = new HashSet>(); } this.components.Add(component); this.componentDict.Add(component.GetComponentType(), component); return component; } public void AddComponent(Component component) { if (this.componentDict.ContainsKey(component.GetComponentType())) { throw new Exception( string.Format("AddComponent, component already exist, id: {0}, component: {1}", this.Id, component.GetComponentType().Name)); } if (this.components == null) { this.components = new HashSet>(); } this.components.Add(component); this.componentDict.Add(component.GetComponentType(), component); } public void RemoveComponent() where K : Component { Component component; if (!this.componentDict.TryGetValue(typeof (K), out component)) { throw new Exception( string.Format("RemoveComponent, component not exist, id: {0}, component: {1}", this.Id, typeof (K).Name)); } this.components.Remove(component); this.componentDict.Remove(typeof (K)); if (this.components.Count == 0) { this.components = null; } } public K GetComponent() where K : Component { Component component; if (!this.componentDict.TryGetValue(typeof (K), out component)) { return default (K); } return (K) component; } public Component[] GetComponents() { return this.components.ToArray(); } public override void BeginInit() { base.BeginInit(); this.components = new HashSet>(); this.componentDict = new Dictionary>(); } public override void EndInit() { base.EndInit(); if (this.components.Count == 0) { this.components = null; return; } foreach (Component component in this.components) { component.Owner = (T) this; this.componentDict.Add(component.GetComponentType(), component); } } } }