DataCache.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. using System.Collections.Generic;
  2. namespace Rokid.UXR
  3. {
  4. /// <summary>
  5. /// Data Cache
  6. /// </summary>
  7. public class DataCache : Singleton<DataCache>
  8. {
  9. Dictionary<string, object> data = new Dictionary<string, object>();
  10. /// <summary>
  11. /// Add Data
  12. /// </summary>
  13. /// <param name="key"></param>
  14. /// <param name="value"></param>
  15. /// <param name="cover"></param>
  16. public void Add(string key, object value, bool cover = false)
  17. {
  18. if (data.ContainsKey(key) && cover == false)
  19. {
  20. RKLog.KeyInfo($"====DataCache=== Add Key Repetition {key}: {value}");
  21. return;
  22. }
  23. else if (data.ContainsKey(key) && cover == true)
  24. {
  25. data[key] = value;
  26. }
  27. else
  28. {
  29. data.Add(key, value);
  30. }
  31. }
  32. /// <summary>
  33. /// Add Data
  34. /// </summary>
  35. /// <param name="value"></param>
  36. /// <param name="cover"></param>
  37. public void Add(object value, bool cover = false)
  38. {
  39. string key = value.GetType().FullName;
  40. Add(key, value, cover);
  41. }
  42. /// <summary>
  43. /// Update Data
  44. /// </summary>
  45. /// <param name="key"></param>
  46. /// <param name="value"></param>
  47. public void UpdateData(string key, object value)
  48. {
  49. if (data.ContainsKey(key))
  50. {
  51. data[key] = value;
  52. }
  53. else
  54. {
  55. RKLog.KeyInfo($"====DataCache=== UpdateData Key Repetition {key}: {value}");
  56. }
  57. }
  58. /// <summary>
  59. /// Get Value
  60. /// </summary>
  61. /// <typeparam name="T"></typeparam>
  62. /// <param name="key"></param>
  63. /// <returns></returns>
  64. public T Get<T>(string key)
  65. {
  66. object obj = null;
  67. if (data.TryGetValue(key, out obj))
  68. {
  69. return (T)obj;
  70. }
  71. else
  72. {
  73. RKLog.KeyInfo($"====DataCache=== Get Key Not Exist {key}");
  74. }
  75. return default;
  76. }
  77. /// <summary>
  78. /// Get Value
  79. /// </summary>
  80. /// <typeparam name="T">Data Object</typeparam>
  81. /// <param name="key">Data Key</param>
  82. /// <returns></returns>
  83. public T Get<T>()
  84. {
  85. string key = typeof(T).FullName;
  86. return Get<T>(key);
  87. }
  88. /// <summary>
  89. /// Get All Keys
  90. /// </summary>
  91. /// <returns></returns>
  92. public List<string> Keys()
  93. {
  94. return new List<string>(data.Keys);
  95. }
  96. /// <summary>
  97. /// Clear Data
  98. /// </summary>
  99. public void Clear()
  100. {
  101. data.Clear();
  102. }
  103. }
  104. }