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