Env.cs 1.5 KB

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