You don't actually need anything special here... since protobuf-net respects inheritance. If you have:
[ProtoInclude(typeof(Foo), 20)]
[ProtoInclude(typeof(Bar), 21)]
public abstract class MyBase {
/* other members */
public byte[] GetBytes()
{
using(MemoryStream ms = new MemoryStream())
{
Serializer.Serialize<MyBase>(ms, this); // MyBase can be implicit
return ms.ToArray();
}
}
}
[ProtoContract]
class Foo : MyBase { /* snip */ }
[ProtoContract]
class Bar : MyBase { /* snip */ }
then it will work. To serialize the data, it always starts at the base (contract) type; so even if you did Serializer.Serialize<Foo>(stream, obj)
the first thing it will do is detect that it has a base class that is a contract, and switch to MyBase
. During deserialization it will identify the correct derived (concrete) type and use that, so you can use Deserialize
with MyBase
too, and it will construct a Foo
or Bar
depending on what the original data was.
Thus the following are largely identical:
Serializer.Serialize<BaseType>(dest, obj);
...
BaseType obj = Serializer.Deserialize<BaseType>(source);
and
Serializer.Serialize<DerivedType>(dest, obj);
...
DerivedType obj = Serializer.Deserialize<DerivedType>(source);
The main difference here is how the variables are typed.