2013-02-19 67 views
3

我試圖使用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的各種問題,並且它們與這個例子有點不同(據我瞭解它們)。

回答

8

你會踢你自己。該代碼是除了一件事很好 - 你忘了退流:

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

因爲它是,在Deserialize正在閱讀0字節(因爲它是在結束),從而試圖創建父類型。根據protobuf規範,空流是完全有效的 - 它只是意味着沒有任何有趣值的對象。

+1

哦。我的。哎呀。說真的,我在這方面花的時間比我應有的要長。非常感謝! – Cornstalks 2013-02-19 05:21:38

+3

@Cornstalks我確實說你會踢自己:)但嚴重:謝謝發佈一個可重複的例子 - 它使*更容易協助。 – 2013-02-19 05:25:11

+1

自助遊登記入住,謝謝! – thumbmunkeys 2014-11-04 11:57:08