最简单的 protobuf-net 示例需要帮助
观察下面这段简单的代码:
[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 中也不起作用。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用 SerializeWithLengthPrefix/DeserializeWithLengthPrefix 方法才能从流中检索单个对象。这应该有效:
You have to use the SerializeWithLengthPrefix/ DeserializeWithLengthPrefix methods in order to retrieve a single object from you stream. this should be working: