Protobuf-net未序列化列表



我目前正在试用protobuf-net(v3.0.29(,并尝试序列化/反序列化一些简单的类。从最简单的工作示例来看,我不明白为什么protobuf-net将简单的List<int> Value序列化/反序列化为一个没有元素的列表。

public enum BigEnum { One, Two }
[ProtoContract]
public class Container
{
[ProtoMember(1)]
public BigEnum Parameter { get; private set; }
[ProtoMember(2)]
public List<int> Value { get; set; }
public Container()
{
Parameter = BigEnum.One;
Value = new List<int>();
}
}
static class Program
{
static void Main(string[] args)
{
Container data = new Container();
data.Value.Add(-1);
data.Value.Add(1);
MemoryStream memStream = new MemoryStream();
Serializer.Serialize<Container>(memStream, data);
var result = Serializer.Deserialize<Container>(memStream);
}
}

这个protobuf文件是由Serializer.GetProto((生成的,对我来说很好。我们如何正确处理List<int> Value,以及protobuf-net如何处理更复杂的结构,如List<KeyValuePair<String, String>>还是Dictionary<int,double>?protobuf-net有一些非常古老的帖子,里面有字典,但我不知道目前的状态。

syntax = "proto3";
package NetCoreProtobuf;
enum BigEnum {
One = 0;
Two = 1;
}
message Container {
BigEnum Parameter = 1;
repeated int32 Value = 2 [packed = false];
}

非常简单:您没有倒带流,所以它从当前位置读取,位于流的末尾,读取的字节为零。碰巧在protobuf中,零字节是完全有效的,所以它不能真正引发异常,因为反序列化零字节可能完全正确。

Serializer.Serialize<Container>(memStream, data);
memStream.Position = 0;
var result = Serializer.Deserialize<Container>(memStream);

或者更简单:使用DeepClone方法:

var clone = Serializer.DeepClone(data);

最新更新