Entity.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. T t = new T { Owner = this };
  21. this.Components.Add(t);
  22. this.ComponentDict.Add(typeof (T), t);
  23. }
  24. public void RemoveComponent<T>() where T : Component
  25. {
  26. Component t;
  27. this.ComponentDict.TryGetValue(typeof(T), out t);
  28. this.Components.Remove(t);
  29. this.ComponentDict.Remove(typeof(T));
  30. }
  31. public T GetComponent<T>() where T : Component
  32. {
  33. Component t;
  34. if (!this.ComponentDict.TryGetValue(typeof (T), out t))
  35. {
  36. return null;
  37. }
  38. return (T) t;
  39. }
  40. public Component[] GetComponents()
  41. {
  42. return this.Components.ToArray();
  43. }
  44. public virtual void BeginInit()
  45. {
  46. }
  47. public virtual void EndInit()
  48. {
  49. foreach (Component component in this.Components)
  50. {
  51. this.ComponentDict.Add(component.GetType(), component);
  52. component.Owner = this;
  53. }
  54. }
  55. }
  56. }