Entity.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using MongoDB.Bson.Serialization.Attributes;
  5. namespace Common.Base
  6. {
  7. public abstract class Entity : Object
  8. {
  9. [BsonElement]
  10. [BsonIgnoreIfNull]
  11. private HashSet<Component> components;
  12. private Dictionary<Type, Component> componentDict = new Dictionary<Type, Component>();
  13. public T AddComponent<T>() where T : Component, new()
  14. {
  15. if (this.componentDict.ContainsKey(typeof (T)))
  16. {
  17. throw new Exception(
  18. string.Format("AddComponent, component already exist, id: {0}, component: {1}",
  19. this.Id, typeof(T).Name));
  20. }
  21. if (this.components == null)
  22. {
  23. this.components = new HashSet<Component>();
  24. }
  25. T t = new T { Owner = this };
  26. this.components.Add(t);
  27. this.componentDict.Add(typeof (T), t);
  28. return 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. if (this.components.Count == 0)
  42. {
  43. this.components = null;
  44. }
  45. }
  46. public T GetComponent<T>() where T : Component
  47. {
  48. Component t;
  49. if (!this.componentDict.TryGetValue(typeof (T), out t))
  50. {
  51. throw new Exception(
  52. string.Format("GetComponent, component not exist, id: {0}, component: {1}",
  53. this.Id, typeof(T).Name));
  54. }
  55. return (T) t;
  56. }
  57. public Component[] GetComponents()
  58. {
  59. return this.components.ToArray();
  60. }
  61. public override void BeginInit()
  62. {
  63. base.BeginInit();
  64. this.components = new HashSet<Component>();
  65. this.componentDict = new Dictionary<Type, Component>();
  66. }
  67. public override void EndInit()
  68. {
  69. base.EndInit();
  70. if (this.components.Count == 0)
  71. {
  72. this.components = null;
  73. return;
  74. }
  75. foreach (Component component in this.components)
  76. {
  77. component.Owner = this;
  78. this.componentDict.Add(component.GetType(), component);
  79. }
  80. }
  81. }
  82. }