I am trying to write a custom protobuf-net serializer to put a property of type object to the wire.
[ProtoContract(Serializer=typeof(ChangeRecordSerializer))]
public class ChangeRecord
{
public object NewValue {get;set;}
}
This is where I'm at:
public class ChangeRecordSerializer : ISerializer<ChangeRecord>
{
public void Write(ref ProtoWriter.State state, ChangeRecord value)
{
state.WriteString(1, value.NewValue.GetType().FullName;
// how to serialize value.NewValue???
}
public void Read(ref ProtoReader.State state, ChangeRecord value)
{
int num = 0;
string typeName = null;
while ((num = state.ReadFieldHeader()) > 0)
{
switch (num)
{
case 1:
typeName = state.ReadString();
break;
case 2:
var type = Type.GetType(typeName);
// how to read value.NewValue???
break;
}
}
}
public SerializerFeatures Features => SerializerFeatures.CategoryMessage | SerializerFeatures.WireTypeString;
}
How do I implement the two commented out lines?
The problem with using a custom serializer is that (at least currently) once you're at that level: you need to stay at that level - meaning: you can't just get the serializer to handle all the expected types: it is expecting you to be explicit from there downwards, which gets very awkward. If this was me, I would just use a surrogate, having the surrogate work similarly to a discriminated union. This doesn't need to be expensive; consider: