MongoHelper.cs 2.5 KB

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