Protobuf-net serialization error: Dynamic type is not a contract-type: Int32

Protobuf-net serialization error: Dynamic type is not a contract-type: Int32

我需要使用以下代码进行序列化和反序列化。但我在序列化时总是收到“动态类型不是合同类型”错误。我坚持这个。我需要以某种方式实现这一点 有人可以帮助我吗?

using ProtoBuf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

namespace ProtoSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                byte[] arr;
                ClassA obj = new ClassA();
                obj.ColumnList = new List<int> {1 };
                using (var stream = new MemoryStream())
                {
                    ProtoBuf.Serializer.Serialize(stream, obj);
                    arr = stream.ToArray();
                }
                using(var stream=new MemoryStream(arr)) 
                {
                    var result = Serializer.Deserialize(typeof(ClassA), stream);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }
    }
    [ProtoContract]
    public class ClassA 
    {
        [ProtoMember(1,DynamicType =true)]
        public IList ColumnList;
    }
}

大部分复制自 question about protobuf dynamic array

documentation for dynamic arrays状态:

DynamicType - stores additional Type information with the type (by default it includes the AssemblyQualifiedName, although this can be controlled by the user). This makes it possible to serialize weak models, i.e. where object is used for property members, however currently this is limited to contract types (not primitives), and does not work for types with inheritance (these limitations may be removed at a later time). Like with AsReference, this uses a very different layout format

你有一个原语,因此你不能使用 DynamicType。正如您收到的错误消息中所解释的那样。

一种解决方法是将要存储的基元包装在具有已定义契约的另一种类型中。

我强烈建议不要在这里或其他地方使用动态功能。它在 V3 中已被弃用,可能是永久性的。看起来您在这里真正想要的是 struct.proto 中的 Value。这目前在 protobuf-net 中没有内置支持,但我可能会很快添加它。至于现在:我可能会建议使用 具有 那些东西作为字段的类型的数组。如果您使布局看起来像 Value 那样,就字段编号而言,它应该可以在以后直接交换。