使用Protobuf-net序列化可空双打列表时出现问题

我已经能够在没有问题的情况下序列化可以为空的双打,并且可以序列化可以为空的其他类型的列表,但是不能序列化可空双打的列表.

如果我这样做:

        List<double?> aList = new List<double?>();
        aList.Add(0.1);
        aList.Add(null);
        Serializer.Serialize(ms, aList);

我收到此错误:

System.NullReferenceException: Object reference not set to an instance of an object.
at ProtoBuf.Meta.TypeModel.TrySerializeAuxiliaryType(ProtoWriter writer, Type type, DataFormat format, Int32 tag, Object value, Boolean isInsideList) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 169
at ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 188
at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 217
at ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value) in c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 201
at ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) in c:\Dev\protobuf-net\protobuf-net\Serializer.cs:line 87

这有用吗?难道我做错了什么?

最佳答案 这里的主要问题是protobuf规范根本没有null概念 – 显式null / missing值不能用protobuf格式表示.

在每个库的基础上,库本身可以选择欺骗额外的层来允许这种事情,但是:

>它需要额外的字节在线上
>它会使代码复杂化并需要额外的配置
>它会(必要时)禁用像“压缩”编码这样的优化

它可能应该检测到null并且表现得更好!

我鼓励您序列化具有可空值的事物列表,而不是列出具有空值的列表.例如:

[ProtoContract]
public class Foo {
    [ProtoMember(1)] public double? Value {get;set;}
}

上面的列表可以表示空值.并且基本上与我写的内容完全相同,如果我添加内置支持欺骗空值.

点赞