在Protobuf.NET中序列化List <object>(对象是支持的基元)?

Tim*_*dge 12 c# protobuf-net

如何使用protobuf-net序列化这样的对象:

public class MyObject{
   public string Key {get; set;}
   public List<Object> Values {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

当我尝试使用TypeModel序列化它时,protobuf-net会抛出一个错误,指出它不知道如何序列化System.Object.现在我知道Values只会包含基元(int,string,float,DateTime等).那么我如何让protobuf-net知道这个呢?

Dan*_*ebl 9

从任何意义上讲,这在纯ProtoBuf中都不可行.ProtoBuf是强类型的,但在消息中不包含类型信息; 类型信息始终在外部指定.因此,有两个"好"的解决方案; 即,除Protobuf-net之外的protobuf实现很容易解释的解决方案(您可能会或可能不会关心,但马克肯定似乎).

1:替换List<object>List<PrimitiveType>where PrimitiveType包含与所有12个或者原语类型相对应的可选字段(取决于您对"原语类型"的定义.),并确保每个实例中只填写其中一个.

2:替换List<object>与的组合List<int>,List<double>,List<string>等.