【问题标题】:Protobuf-net not serializing ListProtobuf-net 没有序列化列表
【发布时间】:2021-01-14 05:51:43
【问题描述】:

我目前正在尝试使用 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&lt;int&gt; Value 并且 protobuf-net 可以处理更复杂的结构,例如 List&lt;KeyValuePair&lt;String, String&gt;&gt;Dictionary&lt;int,double&gt; 在班级内? protobuf-net 有一些非常古老的帖子,里面有字典,但我不知道目前的状态是什么。

syntax = "proto3";
package NetCoreProtobuf;

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

【问题讨论】:

    标签: c# protocol-buffers protobuf-net


    【解决方案1】:

    非常简单:您没有倒回流,因此它从 当前 位置读取 - 在流的末尾,读取零字节。恰好是零字节在 protobuf 中完全有效的情况,所以它不能真正引发 这里例外,因为您在反序列化零字节时可能是完全正确的。

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

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

    var clone = Serializer.DeepClone(data);
    

    【讨论】:

    • 谢谢马克。在我的用例中,我使用 Windows NamedPipes 作为内存流,但最后我放弃了它并选择了NetMQ。无论如何,这个答案是正确的。
    猜你喜欢
    • 2012-08-31
    • 2013-06-16
    • 1970-01-01
    • 2011-10-03
    • 2012-04-26
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    相关资源
    最近更新 更多