Entity.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using MongoDB.Bson.Serialization.Attributes;
  6. namespace Common.Base
  7. {
  8. public abstract class Entity : Object, ISupportInitialize
  9. {
  10. [BsonElement]
  11. private HashSet<Component> Components { get; set; }
  12. private Dictionary<Type, Component> ComponentDict { get; set; }
  13. protected Entity()
  14. {
  15. this.Components = new HashSet<Component>();
  16. this.ComponentDict = new Dictionary<Type, Component>();
  17. }
  18. public void AddComponent<T>() where T : Component, new()
  19. {
  20. if (this.ComponentDict.ContainsKey(typeof (T)))
  21. {
  22. throw new Exception(
  23. string.Format("AddComponent, component already exist, id: {0}, component: {1}",
  24. this.Id, typeof(T).Name));
  25. }
  26. T t = new T { Owner = this };
  27. this.Components.Add(t);
  28. this.ComponentDict.Add(typeof (T), t);
  29. }
  30. public void RemoveComponent<T>() where T : Component
  31. {
  32. Component t;
  33. if (!this.ComponentDict.TryGetValue(typeof (T), out t))
  34. {
  35. throw new Exception(
  36. string.Format("RemoveComponent, component not exist, id: {0}, component: {1}",
  37. this.Id, typeof(T).Name));
  38. }
  39. this.Components.Remove(t);
  40. this.ComponentDict.Remove(typeof(T));
  41. }
  42. public T GetComponent<T>() where T : Component
  43. {
  44. Component t;
  45. if (!this.ComponentDict.TryGetValue(typeof (T), out t))
  46. {
  47. throw new Exception(
  48. string.Format("GetComponent, component not exist, id: {0}, component: {1}",
  49. this.Id, typeof(T).Name));
  50. }
  51. return (T) t;
  52. }
  53. public Component[] GetComponents()
  54. {
  55. return this.Components.ToArray();
  56. }
  57. public virtual void BeginInit()
  58. {
  59. }
  60. public virtual void EndInit()
  61. {
  62. foreach (Component component in this.Components)
  63. {
  64. component.Owner = this;
  65. this.ComponentDict.Add(component.GetType(), component);
  66. }
  67. }
  68. }
  69. }