2011-05-24 41 views
1

需要遵守以下瑣碎的一段代碼:幫助最瑣碎的protobuf網例如

[ProtoContract] 
    public class B 
    { 
    [ProtoMember(1)] public int Y; 
    } 

    [ProtoContract] 
    public class C 
    { 
    [ProtoMember(1)] public int Y; 
    } 

    class Program 
    { 
    static void Main() 
    { 
     var b = new B { Y = 2 }; 
     var c = new C { Y = 4 }; 
     using (var ms = new MemoryStream()) 
     { 
     Serializer.Serialize(ms, b); 
     Serializer.Serialize(ms, c); 
     ms.Position = 0; 
     var b2 = Serializer.Deserialize<B>(ms); 
     Debug.Assert(b.Y == b2.Y); 
     var c2 = Serializer.Deserialize<C>(ms); 
     Debug.Assert(c.Y == c2.Y); 
     } 
    } 
    } 

第一個斷言失敗! 每個Serialize語句將流位置前進2,所以最後ms.Position是4.但是,在第一個Deserialize語句之後,位置設置爲4,而不是2!實際上,b2.Y等於4,這應該是c2.Y的值!

有一些絕對基本的,我在這裏失蹤。我正在使用protobuf-net v2 r383。

謝謝。

編輯

現在一定是非常愚蠢的,因爲它沒有在V1工作,要麼。

回答

2

您必須使用SerializeWithLengthPrefix/DeserializeWithLengthPrefix方法才能從流中檢索單個對象。這應該是工作:

var b = new B { Y = 2 }; 
var c = new C { Y = 4 }; 
using (var ms = new MemoryStream()) 
{ 
    Serializer.SerializeWithLengthPrefix(ms, b,PrefixStyle.Fixed32); 
    Serializer.SerializeWithLengthPrefix(ms, c, PrefixStyle.Fixed32); 
    ms.Position = 0; 
    var b2 = Serializer.DeserializeWithLengthPrefix<B>(ms,PrefixStyle.Fixed32); 
    Debug.Assert(b.Y == b2.Y); 
    var c2 = Serializer.DeserializeWithLengthPrefix<C>(ms, PrefixStyle.Fixed32); 
    Debug.Assert(c.Y == c2.Y); 
} 
+0

的確。 protobuf規範不包含根消息的任何終止符等。除此之外,我個人更喜歡base-128前綴,因爲這樣可以將數據解釋爲「重複」的元素集合。然而,在基於套接字的代碼中,固定長度前綴很常見。 – 2011-05-24 10:07:37