Tuesday, 15 April 2014

c# - Serializing and Deserializing with Polymorphism and Protobuf-net -



c# - Serializing and Deserializing with Polymorphism and Protobuf-net -

i'm trying utilize protobuf-net serialize objects. i'm not sure if i'm trying inheritance supported, thought i'd check , see if or if i'm doing wrong.

essentially, i'm trying serialize kid class , deserialize back, doing base of operations class reference. demonstrate:

using unityengine; using system.collections; using protobuf; public class main : monobehaviour { // if don't set "skipconstructor = true" // protoexception: no parameterless constructor found parent // ideally, wouldn't have set "skipconstructor = true" can if necessary [protocontract(skipconstructor = true)] [protoinclude(1, typeof(child))] abstract class parent { [protomember(2)] public float floatvalue { get; set; } public virtual void print() { unityengine.debug.log("parent: " + floatvalue); } } [protocontract] class kid : parent { public child() { floatvalue = 2.5f; intvalue = 13; } [protomember(3)] public int intvalue { get; set; } public override void print() { unityengine.debug.log("child: " + floatvalue + ", " + intvalue); } } void start() { kid child = new child(); child.floatvalue = 3.14f; child.intvalue = 42; system.io.memorystream ms = new system.io.memorystream(); // don't *have* this, can, if needed, utilize kid directly. // cool if abstract reference parent abstractreference = child; protobuf.serializer.serialize(ms, abstractreference); protobuf.serializer.deserialize<parent>(ms).print(); } }

this outputs:

parent: 0

what i'd output is:

child: 3.14 42

is possible? , if so, doing wrong? i've read various questions on inheritance , protobuf-net, , they're bit different illustration (as far i've understood them).

you'll kick yourself. code fine except 1 thing - forgot rewind stream:

protobuf.serializer.serialize(ms, abstractreference); ms.position = 0; // <========= add together protobuf.serializer.deserialize<parent>(ms).print();

as was, deserialize reading 0 bytes (because @ end), trying create parent type. empty stream valid in terms of protobuf specification - means object without interesting values.

c# unity3d protocol-buffers protobuf-net

No comments:

Post a Comment