C#protobuf-net反序列化某些属性值时始终为-1

标签 c# protobuf-net

我不确定这个问题是错误还是只是这个,之前我没注意到。

我创建了一个 Document 类并声明了 protobuf-net 限制。

[ProtoContract]
public class Document
{
    [ProtoMember(1)]
    private Dictionary<string,string> _items;

    [ProtoMember(2)]
    public int DocNumber
    {
        get;
        set;
    }

    public Document()
    {
        this.DocNumber = -1;
        this._items = new Dictionary<string,string>();    
    }

    public byte[] Serialize()
    {
        byte[] bytes = null;
        using (var ms = new MemoryStream())
        {
            Serializer.Serialize(ms, this);
            bytes = ms.ToArray();
            ms.Close();
        }
        return bytes;           
    }

    public static Document Deserialize(byte[] bytes)
    {
        Document obj = null;
        using (var ms = new MemoryStream(bytes))
        {
            obj = Serializer.Deserialize<Document>(ms);
            ms.Close();
        }
        return obj;
    }
 }

在测试代码中:

  var doc = new Document();
  doc.DocNumber = 0;          
  var bytes = doc.Serialize();
  var new_doc = Document.Deserialize(bytes);
  Console.WriteLine(new_doc.DocNumber + " vs " + doc.DocNumber);

输出信息是:-1 vs 0。我不敢相信这个结果(正确的结果是0 vs 0),所以我改变了doc.DocNumber = 0doc.DocNumber = 1, 输出是正确的:1 vs 1

这个问题意味着我无法将零分配给 DocNumber 属性,在文档的构造方法中我必须声明 DocNumber 属性为 -1。

有人可以帮助我吗?这个问题是我的原因还是protobuf-net的原因?谢谢。

最佳答案

默认。它假定零值作为默认值。我对这个设计选择感到遗憾,所以它可以在 v2 中禁用,但为了兼容性而保留。在 v1 和 v2 中,您也可以简单地告诉它 -1 是默认值:

[ProtoMember(2), DefaultValue(-1)]
public int DocNumber

关于C#protobuf-net反序列化某些属性值时始终为-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10467708/

相关文章:

c# - 在 Protobuf-net 中,是否可以序列化非装饰类?

c# - 以编程方式在 MS Word 中打开 xml 文件

C# 方法参数是类的属性

c# - 有没有办法将韩语单词分解成/从单个辅音/元音组成?

c# - 如何刷新 Protobuf-net writer

c# - 在不标记成员的情况下使用 ProtoBuf.NET 进行序列化

c# - 尝试读取流末尾时没有无参数构造函数异常

protobuf-net - protobuf-net 中日期时间的 .proto 消息是什么

c# - 使用 LINQ 语法帮助需要

c# - C# 中的乌尔都语语音识别