Env.cs 1.6 KB

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