首页 > 解决方案 > Protobuf-net 序列化错误:动态类型不是合约类型: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;
    }
}

标签: c#serializationprotocol-buffersprotobuf-net

解决方案


主要是从有关 protobuf 动态数组的问题中复制的。

动态数组的文档状态:

DynamicType - 与类型一起存储附加类型信息(默认情况下它包括 AssemblyQualifiedName,尽管这可以由用户控制)。这使得序列化弱模型成为可能,即对象用于属性成员,但是目前这仅限于合同类型(不是原语),并且不适用于具有继承的类型(这些限制可能会在以后删除) . 与 AsReference 一样,它使用非常不同的布局格式

您有一个原语,因此您不能使用 DynamicType。如您收到的错误消息中所述。

一种解决方法可能是将要存储的原语包装在具有已定义合同的另一种类型中。


推荐阅读