How do I use a list / array of some object inheritance with Protobuf / Protobuf-net?

Using Protobuf / Protobuf-net and two classes, one base class and the other derived from base.
How would you serialize / deserialize a list?

For example:

public class SomeBase
{
    ...
}

public class SomeDerived : SomeBase
{
    ...
}

      

And the next serializable field:

public List<SomeBase> SomeList;

      

Keep in mind that the list contains SomeBase and SomeDerived objects.

+2


source to share


1 answer


To get this to work, you just need to assign a tag (number) that it will use to identify the subtype. Basically, the protocol buffers explorer specification does not handle inheritance, so protobuf-net achieves this by modeling inheritance as encapsulation. You are assigning properties / fields to tags with [ProtoMember]

and subtyping through [ProtoInclude]

(compare with [XmlInclude]

).

Note that tags must be unique in any one type, but they can be reused in subtypes - as shown in the example by both levels using tag 1.



Same:

using System.Collections.Generic;
using ProtoBuf;

[ProtoContract]
[ProtoInclude(20, typeof(SomeDerived))]
public class SomeBase
{
    [ProtoMember(1)]
    public string BaseProp { get; set; }
}
[ProtoContract]
public class SomeDerived : SomeBase
{
    [ProtoMember(1)]
    public int DerivedProp { get; set; }
}
[ProtoContract]
public class SomeEntity
{
    [ProtoMember(1)]
    public List<SomeBase> SomeList;
}

class Program
{
    static void Main()
    {
        SomeEntity orig = new SomeEntity
        {
            SomeList = new List<SomeBase> {
                new SomeBase { BaseProp = "abc"},
                new SomeDerived { BaseProp = "def", DerivedProp = 123}
            }
        };
        var clone = Serializer.DeepClone(orig);
        // clone now has a list with 2 items, one each SomeBase and SomeDerived
    }
}

      

+3


source







All Articles