Object.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System.Collections.Generic;
  2. using System.ComponentModel;
  3. using MongoDB.Bson;
  4. using MongoDB.Bson.Serialization.Attributes;
  5. namespace Common.Base
  6. {
  7. public abstract class Object: ISupportInitialize
  8. {
  9. [BsonId]
  10. public ObjectId Id { get; protected set; }
  11. [BsonElement]
  12. [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 object this[string key]
  23. {
  24. get
  25. {
  26. return this.values[key];
  27. }
  28. set
  29. {
  30. if (this.values == null)
  31. {
  32. this.values = new Dictionary<string, object>();
  33. }
  34. this.values[key] = value;
  35. }
  36. }
  37. public T Get<T>(string key)
  38. {
  39. if (!this.values.ContainsKey(key))
  40. {
  41. return default(T);
  42. }
  43. return (T) this.values[key];
  44. }
  45. public T Get<T>()
  46. {
  47. return this.Get<T>(typeof (T).Name);
  48. }
  49. public void Set(string key, object obj)
  50. {
  51. if (this.values == null)
  52. {
  53. this.values = new Dictionary<string, object>();
  54. }
  55. this.values[key] = obj;
  56. }
  57. public void Set<T>(T obj)
  58. {
  59. if (this.values == null)
  60. {
  61. this.values = new Dictionary<string, object>();
  62. }
  63. this.values[typeof (T).Name] = obj;
  64. }
  65. public bool Contain(string key)
  66. {
  67. return this.values.ContainsKey(key);
  68. }
  69. public bool Remove(string key)
  70. {
  71. bool ret = this.values.Remove(key);
  72. if (this.values.Count == 0)
  73. {
  74. this.values = null;
  75. }
  76. return ret;
  77. }
  78. public virtual void BeginInit()
  79. {
  80. if (this.values == null)
  81. {
  82. this.values = new Dictionary<string, object>();
  83. }
  84. }
  85. public virtual void EndInit()
  86. {
  87. if (this.values.Count == 0)
  88. {
  89. this.values = null;
  90. }
  91. }
  92. }
  93. }