[英]How to serialize arrays?
症状:没有为类型定义序列化程序: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>();
我应该使用RuntimeTypeModel注册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 url):
有一个基类型类项的列表。
包裹每种类型。 例如
class TheBase{}
class ArrayOfInt { public int[] value;}
然后,它将成为转换到包装器列表之一。 有更简单的方法吗?
protobuf-net真的很想了解你正在序列化的数据; 拥有Array
是不够的,因为它无法映射到任何protobuf定义。 重复数据(概念上,数组)在protobuf规范中具有非常简洁且非常具体的表示,这不允许额外的空间来单独说出“[x]”。 在protobuf中,预计“[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压缩的垫片)。
为什么不尝试像这样创建一个新的ISerializable对象
[Serializable()]
public class ArrayOfInt : ISerializable
{
public Array ....etc
并从ISerializable接口覆盖GetObjectData()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.