问题描述
症状:没有找到类型定义的串行:System.Array的
Symptom: No serializer defined for type: System.Array
由于所有的C#阵列从Array类继承,我认为这会在protobuf网是有效的
Since all C# arrays inherit from the Array class, I thought that this would be valid in ProtoBuf-net
[ProtoMember(1)]
public Array SomeKindOfArray = new int[]{1,2,3,4,5};
[ProtoMember(2)]
public List<Array> SomeKindOfList = new List<Array>();
我必须要注册阵列与RuntimeTypeModel?
Should I register Array with the RuntimeTypeModel?
m.Add(typeof (Array), true); // does not seem to help
尝试:
Attempts:
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网址现在):
Another possible solution (can't find the SO url right now):
有一个列表基类型类项目。
Have a list of a base type class items.
总结每种类型。例如
class TheBase{}
class ArrayOfInt { public int[] value;}
的
随后将成为转换和从包装的一个列表中的一个。 ?是否有期待更简单的方法。
The would then become one of converting to and from a list of wrappers. Is there an easier way forward?
推荐答案
protobuf网真的想了解你的序列化数据;这是不够的,有阵列
,因为不能映射到任何protobuf的定义。重复数据(概念,数组)已在protobuf的规格非常简洁,非常具体的代表性,这不允许额外的空间这么说,在个人基础上,的[X]。在protobuf的,有[X]预计将已经知道并提前的
protobuf-net really really wants to understand the data you are serializing; it isn't enough to have Array
, as that can't map to any protobuf definition. Repeated data (conceptually, arrays) has a very terse and very specific representation in the protobuf specification, which does not allow extra room for saying, on an individual basis, "of [x]". In protobuf, the "of [x]" is expected to be already known and fixed in advance.
所以固定的:
[ProtoMember(1)]
public int[] AnIntegerArray {get;set;}
[ProtoMember(2)]
public Customer[] ACustomerArray {get;set;}
将工作精细。但阵列
将不会在所有的工作。
will work fine. But Array
will not work at all.
根据这是多么重要,可能还有其它选项,例如,(你可能需要调整的名字!):
Depending on how important this is, there may be other options, for example (and you may want to tweak the names!):
[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网可以使用来实现继承。(这也从技术上讲,是不是在protobuf的规范所支持 - 这是protobuf网在挤压垫片)
would work, I suspect (untested). With classes, there is a little extra room that protobuf-net can use to implement inheritance (which also, technically, isn't supported in the protobuf specification - this is a shim that protobuf-net squeezes in).
这篇关于如何序列化数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!