Object.cs 2.9 KB

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