【发布时间】:2020-06-24 12:10:08
【问题描述】:
我需要使用以下代码进行序列化和反序列化。但是我在序列化时总是收到“动态类型不是合同类型”错误。我被这个困住了。我需要以某种方式实现这一点有人可以帮助我吗?
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;
}
}
【问题讨论】:
-
这里的目标是什么?例如,您想序列化一个可以同时包含“int”和“float”的列表吗?
-
在我的情况下,我将有一个列表,该列表将在运行时分配值,类型将在运行时决定。列表中只有一种类型,而不是多种类型...得到答案来自马克..谢谢
标签: c# serialization protocol-buffers protobuf-net