MongoHelper.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. using MongoDB.Bson;
  5. using MongoDB.Bson.IO;
  6. using MongoDB.Bson.Serialization;
  7. using MongoDB.Bson.Serialization.Serializers;
  8. namespace ETModel
  9. {
  10. public static class MongoHelper
  11. {
  12. static MongoHelper()
  13. {
  14. Type bsonClassMap = typeof(BsonClassMap);
  15. MethodInfo methodInfo = bsonClassMap.GetMethod("RegisterClassMap", new Type[] { });
  16. Type[] types = typeof(Game).Assembly.GetTypes();
  17. foreach (Type type in types)
  18. {
  19. if (!type.IsSubclassOf(typeof(Component)))
  20. {
  21. continue;
  22. }
  23. methodInfo.MakeGenericMethod(type).Invoke(null, null);
  24. }
  25. BsonSerializer.RegisterSerializer(new EnumSerializer<NumericType>(BsonType.String));
  26. }
  27. public static string ToJson(object obj)
  28. {
  29. return obj.ToJson();
  30. }
  31. public static string ToJson(object obj, JsonWriterSettings settings)
  32. {
  33. return obj.ToJson(settings);
  34. }
  35. public static T FromJson<T>(string str)
  36. {
  37. return BsonSerializer.Deserialize<T>(str);
  38. }
  39. public static object FromJson(Type type, string str)
  40. {
  41. return BsonSerializer.Deserialize(str, type);
  42. }
  43. public static byte[] ToBson(object obj)
  44. {
  45. return obj.ToBson();
  46. }
  47. public static object FromBson(Type type, byte[] bytes)
  48. {
  49. return BsonSerializer.Deserialize(bytes, type);
  50. }
  51. public static object FromBson(Type type, byte[] bytes, int index, int count)
  52. {
  53. using (MemoryStream memoryStream = new MemoryStream(bytes, index, count))
  54. {
  55. return BsonSerializer.Deserialize(memoryStream, type);
  56. }
  57. }
  58. public static T FromBson<T>(byte[] bytes)
  59. {
  60. using (MemoryStream memoryStream = new MemoryStream(bytes))
  61. {
  62. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  63. }
  64. }
  65. public static T FromBson<T>(byte[] bytes, int index, int count)
  66. {
  67. return (T) FromBson(typeof (T), bytes, index, count);
  68. }
  69. public static T Clone<T>(T t)
  70. {
  71. return FromBson<T>(ToBson(t));
  72. }
  73. }
  74. }