protobuf 没有正确反序列化对象

protobuf does not deserialize object corrctly

我有三个类:

[ProtoContract]
public class Message
{
    [ProtoMember(1)]
    public int MethodId { set; get; }
    [ProtoMember(2)]
    public CustomArgs Arguments { set; get; }
}

[ProtoContract]
public class CustomArgs
{
    [ProtoMember(1)]
    public int IntVal { set; get; }
    [ProtoMember(2)]
    public string StrVal { set; get; }
    [ProtoMember(3)]
    public CycleData Cd { set; get; }
}

[ProtoContract]
public class CycleData
{
[ProtoMember(1)]
public int Id { set; get; }
[ProtoMember(2, AsReference = true)]
public CycleData Owner { set; get; }}

因此,当我创建对象然后对其进行序列化和反序列化时,Arguments 属性 保持 null 但原始对象具有值。示例代码为:

static void Main(string[] args)
{
    CycleData cd = new CycleData()
    {
        Id = 5
    };
    cd.Owner = cd;

    CustomArgs a = new CustomArgs()
    {
        IntVal = 5,
        StrVal = "string",
        Cd = cd
    };

    Message oldMsg = new Message()
    {
        MethodId = 3,
        Arguments = a
    };

    Stream st = new MemoryStream();
    ProtoBuf.Serializer.Serialize(st, oldMsg);
    var newMsg = ProtoBuf.Serializer.Deserialize<Message>(st);

}

所以newMsg.Arguments反序列化后为空。我做错了什么?

你有一个简单的错误。一旦你 serialize/write 到 memstream,.Pointer 就会留在流的末尾。在同一流上使用后立即反序列化失败,因为在那之后没有任何内容可读。只需重置它:

using (Stream st = new MemoryStream())
{ 
    ProtoBuf.Serializer.Serialize(st, oldMsg);
    st.Position = 0;          // point to start of stream
    var newMsg = ProtoBuf.Serializer.Deserialize<Message>(st);
}

我也把流放在using块中处理了。