I am using Protobuf.net to serialize some classes. I would like to be able to serialize the SuperHero class (below) without having to specify [ProtoInclude] on the base class. This is because the derived classes are automatically generated but the base class is not, so the base class does not directly know about its derived classes.
[ProtoContract]
class Person
{
[ProtoMember(1)]
public int Id { get; set; }
[ProtoMember(2)]
public string Name { get; set; }
}
[ProtoContract]
class SuperHero : Person
{
[ProtoMember(3)]
public string Powers { get; set; }
}
I am using the latest version of protobuf.net.
First a note: at some point, your code must know about the subclass - perhaps via configuration. It is important that somehow you are able to reliably reproduce numbers for each subtype. Incrementing a counter as you find the types at runtime is not sufficient if you are storing data to disk etc, as you might not find the types in the same order next time it runs. So; let's assume that via some mechanism you have a unique positive integer that represents SuperHero as a subclass of Person:
int tag = 7; // why not
Type subType = typeof(SuperHero);
Then, to tell protobuf-net about this sub-type:
RuntimeTypeModel.Default.Add(typeof(Person), true).AddSubType(tag, subType);
This is equivalent to what the attribute-processing code does when it sees [ProtoInclude(...)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With