C#protobuf-net - 默认值覆盖protobuf数据的值

时间:2015-08-28 13:54:47

标签: c# protobuf-net

我需要使用protobuf-net进行serialize/deserialize课程。对于我的类的一些属性,我需要定义一个默认值。我通过设置属性的值来做到这一点。在某些情况下,此默认值会覆盖protobuf数据中的值。

代码示例:

public class Program
{
    static void Main(string[] args)
    {
        var target = new MyClass
        {
            MyBoolean = false
        };

        using (var stream = new MemoryStream())
        {
            Serializer.Serialize(stream, target);
            stream.Position = 0;
            var actual = Serializer.Deserialize<MyClass>(stream);
            //actual.MyBoolean will be true
        }
    }
}

[ProtoContract(Name = "MyClass")]
public class MyClass
{
    #region Properties

    [ProtoMember(3, IsRequired = false, Name = "myBoolean", DataFormat = DataFormat.Default)]
    public Boolean MyBoolean { get; set; } = true;

    #endregion
}
反序列化数据后,

MyBoolean的值为true。

如何解决此问题?

1 个答案:

答案 0 :(得分:8)

出于性能原因,默认值根本不是序列化的。 bool的默认值为false。您的默认值为true。要完成这项工作,您必须使用DefaultValueAttribute

来表示默认值
    [ProtoMember( 3, IsRequired = false, Name = "myBoolean", DataFormat =  DataFormat.Default )]
    [DefaultValue(true)]
    public Boolean MyBoolean { get; set; } = true;
相关问题