简体   繁体   English

Protobuf-net 未序列化列表

[英]Protobuf-net not serializing List

I am currently experimenting with protobuf-net (v3.0.29) and trying to serialize/deserialize some simple classes.我目前正在试验 protobuf-net (v3.0.29) 并尝试序列化/反序列化一些简单的类。 From the minimal working example, I do not understand why protobuf-net serializes/deserializes the simple List<int> Value to a list with no elements.从最小的工作示例来看,我不明白为什么 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);
        }
    }

This protobuf-file was generated by Serializer.GetProto() and looks fine to me.这个 protobuf 文件是由Serializer.GetProto()生成的,对我来说看起来不错。 How can we process List<int> Value correctly and can protobuf-net handle more complex structures like List<KeyValuePair<String, String>> or Dictionary<int,double> within a class?我们如何正确处理List<int> Value以及 protobuf-net 能否在类中处理更复杂的结构,如List<KeyValuePair<String, String>>Dictionary<int,double> There are some very old posts for protobuf-net with dictionaries around but I don't know what's the current state. protobuf-net 有一些非常古老的帖子,周围有字典,但我不知道当前状态是什么。

syntax = "proto3";
package NetCoreProtobuf;

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

Very simple: you didn't rewind the stream, so it read from the current position - at the end of the stream, with zero bytes to read.非常简单:您没有倒带流,所以它从当前位置读取 - 在流的末尾,读取零字节。 It happens to be the case that zero bytes is perfectly valid in protobuf, so it can't really raise an exception here, as you might be entirely correct in deserializing zero bytes.恰好是零字节在 protobuf 中完全有效的情况,所以它不能在这里真正引发异常,因为反序列化零字节可能是完全正确的。

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

Or simpler: use the DeepClone method:或者更简单:使用DeepClone方法:

var clone = Serializer.DeepClone(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM