Env.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using MongoDB.Bson.Serialization.Attributes;
  5. namespace Base
  6. {
  7. public class Env: Object
  8. {
  9. [BsonElement, BsonIgnoreIfNull]
  10. private Dictionary<string, object> values = new Dictionary<string, object>();
  11. public object this[string key]
  12. {
  13. get
  14. {
  15. return this.values[key];
  16. }
  17. set
  18. {
  19. if (this.values == null)
  20. {
  21. this.values = new Dictionary<string, object>();
  22. }
  23. this.values[key] = value;
  24. }
  25. }
  26. public T Get<T>(string key)
  27. {
  28. if (this.values == null || !this.values.ContainsKey(key))
  29. {
  30. return default(T);
  31. }
  32. object value = values[key];
  33. try
  34. {
  35. return (T)value;
  36. }
  37. catch (InvalidCastException e)
  38. {
  39. throw new GameException($"不能把{value.GetType()}转换为{typeof(T)}", e);
  40. }
  41. }
  42. public void Set(string key, object obj)
  43. {
  44. if (this.values == null)
  45. {
  46. this.values = new Dictionary<string, object>();
  47. }
  48. this.values[key] = obj;
  49. }
  50. public bool ContainKey(string key)
  51. {
  52. if (this.values == null)
  53. {
  54. return false;
  55. }
  56. return this.values.ContainsKey(key);
  57. }
  58. public void Remove(string key)
  59. {
  60. if (this.values == null)
  61. {
  62. return;
  63. }
  64. this.values.Remove(key);
  65. if (this.values.Count == 0)
  66. {
  67. this.values = null;
  68. }
  69. }
  70. public void Add(string key, object value)
  71. {
  72. if (this.values == null)
  73. {
  74. this.values = new Dictionary<string, object>();
  75. }
  76. this.values[key] = value;
  77. }
  78. public IEnumerator GetEnumerator()
  79. {
  80. return this.values.GetEnumerator();
  81. }
  82. }
  83. }