使用多态和Protobuf-net进行序列化和反序列化

时间:2013-02-19 03:31:39

标签: c# unity3d protocol-buffers protobuf-net

我正在尝试使用protobuf-net来序列化对象。我不确定是否支持我正在尝试继承的内容,但我认为我会检查它是否存在,或者我是否只是做错了。

基本上,我正在尝试序列化一些子类,然后将其反序列化,但只使用基类引用。为了证明:

using UnityEngine;
using System.Collections;
using ProtoBuf;

public class main : MonoBehaviour
{
    // If I don't put "SkipConstructor = true" I get
    // ProtoException: No parameterless constructor found for Parent
    // Ideally, I wouldn't have to put "SkipConstructor = true" but I 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 Child : 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()
    {
        Child child = new Child();
        child.FloatValue = 3.14f;
        child.IntValue   = 42;

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        // I don't *have* to do this, I can, if needed, just use child directly.
        // But it would be cool if I could do it from an abstract reference
        Parent abstractReference = child; 

        ProtoBuf.Serializer.Serialize(ms, abstractReference);

        ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();
    }
}

输出:

  

Parent: 0

我希望输出的内容是:

  

Child: 3.14 42

这甚至可能吗?如果是这样,我做错了什么?我已经阅读了关于继承和protobuf-net的各种问题,它们与这个例子有点不同(据我所知)。

1 个答案:

答案 0 :(得分:9)

你会踢自己。代码很好,除了一件事 - 你忘了回流:

ProtoBuf.Serializer.Serialize(ms, abstractReference);
ms.Position = 0; // <========= add this
ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();

实际上,Deserialize读取0个字节(因为它在最后),因此尝试创建父类型。就protobuf规范而言,空流完全有效 - 它只是一个没有任何有趣值的对象。