【问题标题】:Problems serializing a list of nullable doubles using Protobuf-net使用 Protobuf-net 序列化可空双精度列表的问题
【发布时间】:2013-05-26 03:58:54
【问题描述】:

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

如果我这样做:

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

我收到此错误:

System.NullReferenceException:对象引用未设置为对象的实例。 在 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 在 c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 188 中的 ProtoBuf.Meta.TypeModel.SerializeCore(ProtoWriter writer, Object value) 在 c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 217 中的 ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value, SerializationContext context) 在 c:\Dev\protobuf-net\protobuf-net\Meta\TypeModel.cs:line 201 中的 ProtoBuf.Meta.TypeModel.Serialize(Stream dest, Object value) 在 ProtoBuf.Serializer.Serialize[T](Stream destination, T instance) in c:\Dev\protobuf-net\protobuf-net\Serializer.cs:line 87

这应该有效吗?我是不是做错了什么?

【问题讨论】:

  • 我用List&lt;int?&gt;List&lt;double?&gt;List&lt;string&gt; 一起进行了测试 - 它们在这里的行为都相同
  • 我将重新运行我的测试并返回
  • 我得到相同的行为将所有可为空的类型。我认为以前虽然我有可空类型,但只有可空双精度才能具有实际的空值。为错误信息道歉。本

标签: protobuf-net


【解决方案1】:

这里的主要问题是 protobuf 规范根本没有 null 的概念 - 明确地 null / 缺失值不能用 protobuf 格式表示。

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

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

不过,它应该可以检测到 null 并且表现得更好!

我鼓励您序列化一个具有可空值的事物列表,而不是序列化可空值本身的列表。例如:

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

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

【讨论】:

  • 对我来说很奇怪它适用于其他可为空的类型,但不适用于双精度数。不过你的解释是有道理的,我会使用建议的解决方案,谢谢
  • @mcmillab 等待...它与其他可空对象一起使用??我将进行调查,以仔细检查是否发生了愚蠢的事情。我上面所说的仍然正确(格式限制等)-但我会看看 double 是否有什么特别的地方
猜你喜欢
  • 1970-01-01
  • 2011-01-23
  • 2012-05-08
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多