Entity.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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<K> : Object where K : Entity<K>
  8. {
  9. [BsonElement]
  10. [BsonIgnoreIfNull]
  11. private HashSet<Component<K>> components;
  12. private Dictionary<Type, Component<K>> componentDict = new Dictionary<Type, Component<K>>();
  13. public T AddComponent<T>() where T : Component<K>, 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<K>>();
  24. }
  25. T t = new T { Owner = (K)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<K>
  31. {
  32. Component<K> 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<K>
  47. {
  48. Component<K> t;
  49. if (!this.componentDict.TryGetValue(typeof (T), out t))
  50. {
  51. return default (T);
  52. }
  53. return (T) t;
  54. }
  55. public Component<K>[] GetComponents()
  56. {
  57. return this.components.ToArray();
  58. }
  59. public override void BeginInit()
  60. {
  61. base.BeginInit();
  62. this.components = new HashSet<Component<K>>();
  63. this.componentDict = new Dictionary<Type, Component<K>>();
  64. }
  65. public override void EndInit()
  66. {
  67. base.EndInit();
  68. if (this.components.Count == 0)
  69. {
  70. this.components = null;
  71. return;
  72. }
  73. foreach (var component in this.components)
  74. {
  75. component.Owner = (K)this;
  76. this.componentDict.Add(component.GetType(), component);
  77. }
  78. }
  79. }
  80. }