Object.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using MongoDB.Bson;
  5. using MongoDB.Bson.Serialization.Attributes;
  6. namespace Common.Base
  7. {
  8. public abstract class Object: ISupportInitialize
  9. {
  10. [BsonId]
  11. public ObjectId Id { get; protected set; }
  12. [BsonElement, BsonIgnoreIfNull]
  13. private Dictionary<string, object> values;
  14. protected Object()
  15. {
  16. this.Id = ObjectId.GenerateNewId();
  17. }
  18. protected Object(ObjectId id)
  19. {
  20. this.Id = id;
  21. }
  22. public virtual void BeginInit()
  23. {
  24. if (this.values == null)
  25. {
  26. this.values = new Dictionary<string, object>();
  27. }
  28. }
  29. public virtual void EndInit()
  30. {
  31. if (this.values.Count == 0)
  32. {
  33. this.values = null;
  34. }
  35. }
  36. public object this[string key]
  37. {
  38. get
  39. {
  40. return this.values[key];
  41. }
  42. set
  43. {
  44. if (this.values == null)
  45. {
  46. this.values = new Dictionary<string, object>();
  47. }
  48. this.values[key] = value;
  49. }
  50. }
  51. public T Get<T>(string key)
  52. {
  53. if (!this.values.ContainsKey(key))
  54. {
  55. return default(T);
  56. }
  57. return (T) this.values[key];
  58. }
  59. public T Get<T>()
  60. {
  61. return this.Get<T>(typeof (T).Name);
  62. }
  63. public void Set(string key, object obj)
  64. {
  65. if (this.values == null)
  66. {
  67. this.values = new Dictionary<string, object>();
  68. }
  69. this.values[key] = obj;
  70. }
  71. public void Set<T>(T obj)
  72. {
  73. if (this.values == null)
  74. {
  75. this.values = new Dictionary<string, object>();
  76. }
  77. this.values[typeof (T).Name] = obj;
  78. }
  79. public bool ContainKey(string key)
  80. {
  81. return this.values.ContainsKey(key);
  82. }
  83. public bool Remove(string key)
  84. {
  85. bool ret = this.values.Remove(key);
  86. if (this.values.Count == 0)
  87. {
  88. this.values = null;
  89. }
  90. return ret;
  91. }
  92. public void Add(string key, object value)
  93. {
  94. if (this.values == null)
  95. {
  96. this.values = new Dictionary<string, object>();
  97. }
  98. this.values.Add(key, value);
  99. }
  100. public IEnumerator GetEnumerator()
  101. {
  102. return this.values.GetEnumerator();
  103. }
  104. }
  105. }