KVComponent.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. namespace Base
  5. {
  6. /// <summary>
  7. /// Key Value组件用于保存一些数据
  8. /// </summary>
  9. public class KVComponent : Component
  10. {
  11. [BsonElement]
  12. private readonly Dictionary<string, object> kv = new Dictionary<string, object>();
  13. public void Add(string key, object value)
  14. {
  15. this.kv.Add(key, value);
  16. }
  17. public void Remove(string key)
  18. {
  19. this.kv.Remove(key);
  20. }
  21. public T Get<T>(string key)
  22. {
  23. object k;
  24. if (!this.kv.TryGetValue(key, out k))
  25. {
  26. return default(T);
  27. }
  28. return (T)k;
  29. }
  30. public override void Dispose()
  31. {
  32. if (this.Id == 0)
  33. {
  34. return;
  35. }
  36. base.Dispose();
  37. }
  38. }
  39. public static class KVHelper
  40. {
  41. public static void KVAdd(this Entity entity, string key, object value)
  42. {
  43. entity.GetComponent<KVComponent>().Add(key, value);
  44. }
  45. public static void KVRemove(this Entity entity, string key)
  46. {
  47. entity.GetComponent<KVComponent>().Remove(key);
  48. }
  49. public static void KVGet<T>(this Entity entity, string key)
  50. {
  51. entity.GetComponent<KVComponent>().Get<T>(key);
  52. }
  53. }
  54. }