如何序列化数组

本文关键字:数组 序列化 | 更新日期: 2023-09-27 18:33:30

>症状:没有为类型定义序列化程序:System.Array

由于所有 C# 数组都继承自 Array 类,我认为这在 ProtoBuf-net 中是有效的

[ProtoMember(1)]
public Array SomeKindOfArray = new int[]{1,2,3,4,5};
[ProtoMember(2)]
public List<Array> SomeKindOfList = new List<Array>();

我应该向运行时类型模型注册数组吗?

m.Add(typeof (Array), true);  // does not seem to help

尝试:

new int[]{1,2,3,4} // works
(object)new int[] { 1, 2, 3, 4 } // does not work
(Array)new int[] { 1, 2, 3, 4 } // does not work

另一种可能的解决方案(现在找不到 SO 网址):

具有基类型类项的列表。

包装每种类型。 例如

class TheBase{}
class ArrayOfInt { public int[] value;}

然后,这将成为在包装器列表之间转换和从包装器列表转换之一。 有没有更简单的前进方式?

如何序列化数组

protobuf-net真的想理解你正在序列化的数据;仅仅有Array是不够的,因为这不能映射到任何protobuf定义。重复数据(概念上是数组)在 protobuf 规范中具有非常简洁和非常具体的表示,这不允许在单个基础上说"of [x]"的额外空间。在protobuf中,"of [x]"应该已经知道并提前修复。

所以:

[ProtoMember(1)]
public int[] AnIntegerArray {get;set;}
[ProtoMember(2)]
public Customer[] ACustomerArray {get;set;}

将正常工作。但是Array根本行不通。

根据这的重要性,可能还有其他选项,例如(您可能需要调整名称!

[ProtoContract]
[ProtoInclude(1, typeof(DummyWrapper<int>)]
[ProtoInclude(2, typeof(DummyWrapper<Customer>)]
public abstract class DummyWrapper {
    public abstract Type ElementType {get;}
}
[ProtoContract]
public class DummyWrapper<T> : DummyWrapper {
    [ProtoMember(1)]
    public T[] TheData {get;set;}
    public override Type ElementType {get { return typeof(T); } }
}

跟:

[ProtoMember(1)]
public DummyWrapper TheData {get;set;}

会起作用,我怀疑(未经测试)。对于类,protobuf-net 可以使用一点额外的空间来实现继承(从技术上讲,protobuf 规范也不支持继承 - 这是 protobuf-net 挤进的填充程序)。

你为什么不尝试创建一个新的ISerializedable对象

,像这样
[Serializable()]    
public class ArrayOfInt : ISerializable 
{
    public Array ....etc

并从接口 ISerialize 覆盖 GetObjectData()