StructBsonSerialize.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // using System;
  2. // using System.Reflection;
  3. // using MongoDB.Bson.IO;
  4. // using MongoDB.Bson.Serialization;
  5. // using MongoDB.Bson.Serialization.Serializers;
  6. // using MongoDB.Bson.Serialization.Attributes;
  7. //
  8. // namespace ET
  9. // {
  10. // public class StructBsonSerialize<TValue>: StructSerializerBase<TValue> where TValue : struct
  11. // {
  12. // public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value)
  13. // {
  14. // Type nominalType = args.NominalType;
  15. //
  16. // IBsonWriter bsonWriter = context.Writer;
  17. //
  18. // bsonWriter.WriteStartDocument();
  19. //
  20. // FieldInfo[] fields = nominalType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  21. // foreach (FieldInfo field in fields)
  22. // {
  23. // BsonElementAttribute bsonElement = field.GetCustomAttribute<BsonElementAttribute>();
  24. // if (bsonElement == null && !field.IsPublic)
  25. // {
  26. // continue;
  27. // }
  28. // bsonWriter.WriteName(field.Name);
  29. // BsonSerializer.Serialize(bsonWriter, field.FieldType, field.GetValue(value));
  30. // }
  31. //
  32. // bsonWriter.WriteEndDocument();
  33. // }
  34. //
  35. // public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  36. // {
  37. // //boxing is required for SetValue to work
  38. // object obj = new TValue();
  39. // Type actualType = args.NominalType;
  40. // IBsonReader bsonReader = context.Reader;
  41. //
  42. // bsonReader.ReadStartDocument();
  43. //
  44. // while (bsonReader.State != BsonReaderState.EndOfDocument)
  45. // {
  46. // switch (bsonReader.State)
  47. // {
  48. // case BsonReaderState.Name:
  49. // {
  50. // string name = bsonReader.ReadName(Utf8NameDecoder.Instance);
  51. // FieldInfo field = actualType.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  52. // if (field != null)
  53. // {
  54. // object value = BsonSerializer.Deserialize(bsonReader, field.FieldType);
  55. // field.SetValue(obj, value);
  56. // }
  57. //
  58. // break;
  59. // }
  60. // case BsonReaderState.Type:
  61. // {
  62. // bsonReader.ReadBsonType();
  63. // break;
  64. // }
  65. // case BsonReaderState.Value:
  66. // {
  67. // bsonReader.SkipValue();
  68. // break;
  69. // }
  70. // }
  71. // }
  72. //
  73. // bsonReader.ReadEndDocument();
  74. //
  75. // return (TValue)obj;
  76. // }
  77. // }
  78. // }