Entity.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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, BsonIgnoreIfNull]
  10. private HashSet<Component> components;
  11. private Dictionary<Type, Component> componentDict = new Dictionary<Type, Component>();
  12. public T AddComponent<T>() where T : Component, new()
  13. {
  14. if (this.componentDict.ContainsKey(typeof (T)))
  15. {
  16. throw new Exception(
  17. string.Format("AddComponent, component already exist, id: {0}, component: {1}",
  18. this.Id, typeof(T).Name));
  19. }
  20. if (this.components == null)
  21. {
  22. this.components = new HashSet<Component>();
  23. }
  24. T t = new T { Owner = this };
  25. this.components.Add(t);
  26. this.componentDict.Add(typeof (T), t);
  27. return t;
  28. }
  29. public void RemoveComponent<T>() where T : Component
  30. {
  31. Component t;
  32. if (!this.componentDict.TryGetValue(typeof (T), out t))
  33. {
  34. throw new Exception(
  35. string.Format("RemoveComponent, component not exist, id: {0}, component: {1}",
  36. this.Id, typeof(T).Name));
  37. }
  38. this.components.Remove(t);
  39. this.componentDict.Remove(typeof(T));
  40. if (this.components.Count == 0)
  41. {
  42. this.components = null;
  43. }
  44. }
  45. public T GetComponent<T>() where T : Component
  46. {
  47. Component t;
  48. if (!this.componentDict.TryGetValue(typeof (T), out t))
  49. {
  50. throw new Exception(
  51. string.Format("GetComponent, component not exist, id: {0}, component: {1}",
  52. this.Id, typeof(T).Name));
  53. }
  54. return (T) t;
  55. }
  56. public Component[] GetComponents()
  57. {
  58. return this.components.ToArray();
  59. }
  60. public override void BeginInit()
  61. {
  62. base.BeginInit();
  63. this.components = new HashSet<Component>();
  64. this.componentDict = new Dictionary<Type, Component>();
  65. }
  66. public override void EndInit()
  67. {
  68. base.EndInit();
  69. if (this.components.Count == 0)
  70. {
  71. this.components = null;
  72. return;
  73. }
  74. foreach (Component component in this.components)
  75. {
  76. component.Owner = this;
  77. this.componentDict.Add(component.GetType(), component);
  78. }
  79. }
  80. }
  81. }