2011-09-21 40 views
10

如何序列化对象像这样与protobuf网:Protobuf.NET中的序列化列表<object>(其中对象是受支持的基元)?

public class MyObject{ 
    public string Key {get; set;} 
    public List<Object> Values {get; set;} 
} 

当我尝试用TypeModel protobuf网抛出一个错误,指出它不知道如何序列System.Object的序列化此。现在我知道值只会包含原语(int,string,float,DateTime等)。那么,我该如何让protobuf-net了解这一点?

+0

日期时间不是原始替换List<object>。 –

+0

然而,它是可序列化的。 – cHao

+0

我不知道protobuf,但你从串行器中问了很多。 –

回答

9

这不是纯粹的protobuf确实可行的,在任何意义。 ProtoBuf是强类型的,但不包含消息中的类型信息;类型信息始终在外部指定。因此有两个“好”的解决方案;也就是说,除了Protobuf-net(你可能会也可能不关心,但是马克肯定似乎)之外的protobuf实现可以很容易地解释这些解决方案。

1:List<PrimitiveType>其中PrimitiveType包含对应于所有12或者那么原始类型可选字段(根据您的“原始类型”的定义)更换List<object>,并且可以确保只有其中之一是填补上每个实例。

2:与List<int>的组合,List<double>List<string>

0

In Protobuf-net how can I pass an array of type object with objects of different types inside, knowing the set of potential types in advance

作为每马克柱(Protobuf.NET的作者)object是有问题的。尽管我现在找不到它,但我清楚地记得在源代码中检查了object以针对直接对对象属性进行序列化的尝试抛出异常。

要解决这个你应该使用更具体的类被序列化并不能直接使用object。您可以使用IProtoSerializer来实现自定义序列化/反序列化。如果有帮助,Protobuf也将支持ISerializableIXmlSerializable接口。

+2

澄清:protobuf-net不是*消耗*'ISerializable'和'IXmlSerializable' - 而不是它可以用来实现它们。 'IProtoSerializer'是* internal *类,不能单独使用。 –

+0

@MarcGravell感谢您的澄清。 –

相关问题