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

C# protobuf-net - default value overwrites value from protobuf data

我需要 serialize/deserialize 类 使用 protobuf-net。对于我的 类 的一些属性,我需要定义一个默认值。我通过设置属性的值来做到这一点。在某些情况下,此默认值会覆盖 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。

我该如何解决这个问题?

出于性能原因,默认值根本没有序列化。 bool 的默认值为 false。您的默认值为真。要使这项工作正常进行,您必须使用 DefaultValueAttribute:

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