Entity.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Common.Base
  5. {
  6. public class Entity: Object
  7. {
  8. private readonly Dictionary<string, Component> components = new Dictionary<string, Component>();
  9. public void AddComponent<T>() where T : Component, new()
  10. {
  11. T t = new T { Owner = this };
  12. this.components.Add(typeof(T).Name, t);
  13. }
  14. public void RemoveComponent<T>() where T : Component
  15. {
  16. this.components.Remove(typeof(T).Name);
  17. }
  18. public T GetComponent<T>() where T : Component
  19. {
  20. Component t;
  21. if (!this.components.TryGetValue(typeof (T).Name, out t))
  22. {
  23. throw new Exception(string.Format("not found component: {0}", typeof(T).Name));
  24. }
  25. return (T) t;
  26. }
  27. public T TryGetComponent<T>() where T : Component
  28. {
  29. Component t;
  30. if (!this.components.TryGetValue(typeof(T).Name, out t))
  31. {
  32. return null;
  33. }
  34. return (T) t;
  35. }
  36. public Component[] GetComponents()
  37. {
  38. return this.components.Values.ToArray();
  39. }
  40. }
  41. }