@@ -76,35 +76,37 @@ of the ``BsonSerializer`` class as follows:
76
76
Custom Serializers
77
77
~~~~~~~~~~~~~~~~~~
78
78
79
- In some cases, you might need to create a custom serializer. When creating a
80
- custom serializer, implement the ``SerializerBase<T>`` abstract base class and
81
- override the ``Deserialize()`` and ``Serialize()`` methods.
79
+ To create your own custom serializer, implement the ``IBsonSerializer`` base class, set
80
+ the ``ValueType`` member, and override the ``Deserialize()`` and ``Serialize()`` methods.
82
81
83
82
The following code example shows a custom ``BsonRegularExpression`` serializer:
84
83
85
84
.. code-block:: csharp
86
85
87
- class CustomRegularExpressionSerializer : SerializerBase<Regex>
86
+ class CustomRegularExpressionSerializer : IBsonSerializer
88
87
{
89
- public override Regex Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
90
- {
91
- var type = context.Reader.GetCurrentBsonType();
88
+ public Type ValueType => typeof(Regex);
89
+
90
+ public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
91
+ {
92
+ var type = context.Reader.CurrentBsonType;
92
93
switch (type)
93
94
{
94
- case BsonType.RegularExpression:
95
- return context.Reader.ReadRegularExpression().AsRegex;
96
- case BsonType.String:
97
- var pattern = context.Reader.ReadString();
98
- return new Regex(pattern);
99
- default:
100
- throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression.");
95
+ case BsonType.RegularExpression:
96
+ return context.Reader.ReadRegularExpression().AsRegex;
97
+ case BsonType.String:
98
+ var pattern = context.Reader.ReadString()
99
+ return new Regex(pattern);
100
+ default:
101
+ throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression.");
101
102
}
102
- }
103
-
104
- public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, Regex value)
105
- {
106
- context.Writer.WriteRegularExpression(value);
107
- }
103
+ }
104
+
105
+ public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
106
+ {
107
+ var regex = (Regex) value;
108
+ context.Writer.WriteRegularExpression(regex);
109
+ }
108
110
}
109
111
110
112
Opt-in Interfaces
@@ -155,4 +157,3 @@ guide, see the following API documentation:
155
157
- `SerializerRegistry <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.SerializerRegistry.html>`__
156
158
- `BsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.html>`__
157
159
- `IBsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonSerializer.html>`__
158
- - `SerializerBase<T> <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Serializers.SerializerBase-1.html>`__
0 commit comments