Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protobuf.net: how to handle inheritance without [ProtoInclude]

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.

like image 482
Janik Zikovsky Avatar asked Aug 08 '12 16:08

Janik Zikovsky


1 Answers

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(...)]

like image 131
Marc Gravell Avatar answered Oct 09 '22 02:10

Marc Gravell