开发者

Help needed with the most trivial protobuf-net example

Observe the following trivial piece of code:

  [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);
      }
    }
  }

The first assertion fails! Each Serialize statement advances the stream position by 2, so in the end ms.Position is 4. However, after the first Deserial开发者_运维知识库ize statement, the position is set to 4, rather than 2! In fact, b2.Y equals 4, which should be the value of c2.Y!

There is something absolutely basic, that I am missing here. I am using protobuf-net v2 r383.

Thanks.

EDIT

It must be something really stupid, because it does not work in v1 either.


You have to use the SerializeWithLengthPrefix/ DeserializeWithLengthPrefix methods in order to retrieve a single object from you stream. this should be working:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜