我有三个班级:
[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
但是orignal对象具有值。示例代码为:
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
为空。我做错了什么?
答案 0 :(得分:2)
你有一个简单的错误。序列化/写入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);
}
我还将流放入使用块中进行处理。