Help needed with the most trivial protobuf-net example

被刻印的时光 ゝ 提交于 2019-12-11 13:05:12

问题


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 Deserialize 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.


回答1:


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


来源:https://stackoverflow.com/questions/6107832/help-needed-with-the-most-trivial-protobuf-net-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!