Entity.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 : AMongo
  8. {
  9. [BsonElement]
  10. private HashSet<Component> Components { get; set; }
  11. private Dictionary<Type, Component> ComponentDict { get; set; }
  12. protected Entity()
  13. {
  14. this.Components = new HashSet<Component>();
  15. this.ComponentDict = new Dictionary<Type, Component>();
  16. }
  17. public void AddComponent<T>() where T : Component, new()
  18. {
  19. if (this.ComponentDict.ContainsKey(typeof (T)))
  20. {
  21. throw new Exception(
  22. string.Format("AddComponent, component already exist, id: {0}, component: {1}",
  23. this.Id, typeof(T).Name));
  24. }
  25. T t = new T { Owner = this };
  26. this.Components.Add(t);
  27. this.ComponentDict.Add(typeof (T), 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. }
  41. public T GetComponent<T>() where T : Component
  42. {
  43. Component t;
  44. if (!this.ComponentDict.TryGetValue(typeof (T), out t))
  45. {
  46. throw new Exception(
  47. string.Format("GetComponent, component not exist, id: {0}, component: {1}",
  48. this.Id, typeof(T).Name));
  49. }
  50. return (T) t;
  51. }
  52. public Component[] GetComponents()
  53. {
  54. return this.Components.ToArray();
  55. }
  56. public override void EndInit()
  57. {
  58. foreach (Component component in this.Components)
  59. {
  60. component.Owner = this;
  61. this.ComponentDict.Add(component.GetType(), component);
  62. }
  63. }
  64. }
  65. }