c# protobuf-net when deserialize the some property value always is -1

浪子不回头ぞ 提交于 2019-12-23 20:26:14

问题


i'm not sure this problem whether is the bug or it's just this,before i can't noticed this.

i create a Document class and declare the protobuf-net restrict.

[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;
    }
 }

in the test code:

  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);

the output message is : -1 vs 0.i can't believe this result(the correct result is 0 vs 0),so i change the doc.DocNumber = 0 to doc.DocNumber = 1, the output is correct: 1 vs 1.

this problem means i can't assign the zero to the DocNumber property,in the constructure method of the Document i must be declare the DocNumber property is -1.

someone can help me? this problem is my cause or the protobuf-net cause? thanks.


回答1:


By default. It assumes zero values as defaults. I regret this design choice, so it can be disabled in v2, but is preserved for compatibility. You can, in both v1 and v2, also simply tell it that -1 is the default:

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



回答2:


ProtoBuf does not serialize values that have the .NET default for the type. This behavior is by design as it makes the output more compact.

Since it doesn't know that your constructor assigns a default value to the field, it becomes initialized to -1 (because you have explicit code to do so).

To avoid the problem, use a regular field and assign it the default value, instead of assigning the default in the constructor.



来源:https://stackoverflow.com/questions/10467708/c-sharp-protobuf-net-when-deserialize-the-some-property-value-always-is-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!