gpt4 book ai didi

protobuf-net - 使用 Protobuf-net 序列化可空 double 列表的问题

转载 作者:行者123 更新时间:2023-12-01 02:25:31 25 4
gpt4 key购买 nike

我已经能够毫无问题地序列化可为空的 double 数,并且可以序列化可为空的其他类型的列表,但无法序列化可为空的 double 数的列表。

如果我这样做:

        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 的概念 - 不能以 protobuf 格式明确表示空值/缺失值。

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

  • 线路上会占用额外的字节
  • 它会使代码复杂化并需要额外的配置
  • 它会(必要时)禁用优化,如“打包”编码

  • 不过,它可能应该检测到空值并表现得更好!

    我鼓励您序列化具有可为空值的事物列表,而不是序列化可为空值本身的列表。例如:
    [ProtoContract]
    public class Foo {
    [ProtoMember(1)] public double? Value {get;set;}
    }

    上面的列表可以表示空值。如果我添加了对欺骗空值的内置支持,则基本上与我要写的完全相同。

    关于protobuf-net - 使用 Protobuf-net 序列化可空 double 列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16756104/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com