.net 最简单的protobuf网络示例需要帮助
请遵守以下琐碎的代码:.net 最简单的protobuf网络示例需要帮助,.net,protobuf-net,.net,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 };
[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);
}
}
}
[协议]
公共B级
{
[原成员(1)]公共国际;
}
[原始合同]
公共C类
{
[原成员(1)]公共国际;
}
班级计划
{
静态void Main()
{
var b=新的b{Y=2};
var c=新的c{Y=4};
使用(var ms=new MemoryStream())
{
Serializer.Serialize(ms,b);
Serializer.Serialize(ms,c);
ms.Position=0;
var b2=序列化程序。反序列化(ms);
Assert(b.Y==b2.Y);
var c2=序列化程序。反序列化(ms);
Assert(c.Y==c2.Y);
}
}
}
第一个断言失败了!
每个Serialize语句将流位置提前2,因此最后ms.position是4。但是,在第一个反序列化语句之后,位置设置为4,而不是2!实际上,b2.Y等于4,这应该是c2.Y的值
有一点是绝对基本的,我在这里错过了。我使用的是protobuf net v2 r383
谢谢
编辑
它一定很愚蠢,因为它在v1中也不起作用。为了从流中检索单个对象,必须使用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);
}
varb=newb{Y=2};
var c=新的c{Y=4};
使用(var ms=new MemoryStream())
{
Serializer.SerializeWithLengthPrefix(ms,b,PrefixStyle.Fixed32);
Serializer.SerializeWithLengthPrefix(ms,c,PrefixStyle.Fixed32);
ms.Position=0;
var b2=序列化程序.DeserializeWithLengthPrefix(ms,PrefixStyle.Fixed32);
Assert(b.Y==b2.Y);
var c2=序列化程序.DeserializeWithLengthPrefix(ms,PrefixStyle.Fixed32);
Assert(c.Y==c2.Y);
}
的确如此。protobuf规范不包括根消息的任何终止符等。顺便说一句,我个人更喜欢base-128前缀,因为这允许数据也被解释为一组“重复”的元素。但是,固定长度前缀在基于套接字的代码中非常常见。