BuildContext.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace YooAsset.Editor
  5. {
  6. public class BuildContext
  7. {
  8. private readonly Dictionary<System.Type, IContextObject> _contextObjects = new Dictionary<System.Type, IContextObject>();
  9. /// <summary>
  10. /// 清空所有上下文对象
  11. /// </summary>
  12. public void ClearAllContext()
  13. {
  14. _contextObjects.Clear();
  15. }
  16. /// <summary>
  17. /// 设置上下文对象
  18. /// </summary>
  19. public void SetContextObject(IContextObject contextObject)
  20. {
  21. if (contextObject == null)
  22. throw new ArgumentNullException("contextObject");
  23. var type = contextObject.GetType();
  24. if (_contextObjects.ContainsKey(type))
  25. throw new Exception($"Context object {type} is already existed.");
  26. _contextObjects.Add(type, contextObject);
  27. }
  28. /// <summary>
  29. /// 获取上下文对象
  30. /// </summary>
  31. public T GetContextObject<T>() where T : IContextObject
  32. {
  33. var type = typeof(T);
  34. if (_contextObjects.TryGetValue(type, out IContextObject contextObject))
  35. {
  36. return (T)contextObject;
  37. }
  38. else
  39. {
  40. throw new Exception($"Not found context object : {type}");
  41. }
  42. }
  43. /// <summary>
  44. /// 获取上下文对象
  45. /// </summary>
  46. public T TryGetContextObject<T>() where T : IContextObject
  47. {
  48. var type = typeof(T);
  49. if (_contextObjects.TryGetValue(type, out IContextObject contextObject))
  50. {
  51. return (T)contextObject;
  52. }
  53. else
  54. {
  55. return default;
  56. }
  57. }
  58. }
  59. }