Object.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Collections.Generic;
  2. using MongoDB.Bson;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. namespace Common.Base
  5. {
  6. public abstract class Object
  7. {
  8. [BsonId]
  9. public ObjectId Guid { get; protected set; }
  10. [BsonElement]
  11. [BsonIgnoreIfNull]
  12. private Dictionary<string, object> Values;
  13. protected Object()
  14. {
  15. this.Guid = ObjectId.GenerateNewId();
  16. }
  17. protected Object(ObjectId guid)
  18. {
  19. this.Guid = guid;
  20. }
  21. public object this[string key]
  22. {
  23. set
  24. {
  25. if (this.Values == null)
  26. {
  27. this.Values = new Dictionary<string, object>();
  28. }
  29. this.Values[key] = value;
  30. }
  31. get
  32. {
  33. return this.Values[key];
  34. }
  35. }
  36. public T Get<T>(string key)
  37. {
  38. if (!this.Values.ContainsKey(key))
  39. {
  40. return default(T);
  41. }
  42. return (T) this.Values[key];
  43. }
  44. public T Get<T>()
  45. {
  46. return this.Get<T>(typeof (T).Name);
  47. }
  48. public void Set(string key, object obj)
  49. {
  50. if (this.Values == null)
  51. {
  52. this.Values = new Dictionary<string, object>();
  53. }
  54. this.Values[key] = obj;
  55. }
  56. public void Set<T>(T obj)
  57. {
  58. if (this.Values == null)
  59. {
  60. this.Values = new Dictionary<string, object>();
  61. }
  62. this.Values[typeof (T).Name] = obj;
  63. }
  64. public bool Contain(string key)
  65. {
  66. return this.Values.ContainsKey(key);
  67. }
  68. public bool Remove(string key)
  69. {
  70. bool ret = this.Values.Remove(key);
  71. if (this.Values.Count == 0)
  72. {
  73. this.Values = null;
  74. }
  75. return ret;
  76. }
  77. }
  78. }