在我没有注意到这一点之前,我不确定这个问题是错误还是只是这个。
我创建了一个 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 = 0
更改为 doc.DocNumber = 1
,输出正确:
1 vs 1
。这个问题意味着我不能将零分配给
DocNumber
属性,在 Document 的构造方法中,我必须声明 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/