protobuf-net 未反序列化 0

发布于 2024-08-24 14:09:05 字数 706 浏览 4 评论 0原文

我在 C# 中使用 protobuf-net r278,我刚刚注意到,如果我有一个带有 int 字段的类,如果该字段的值设置为 0,则该字段不会正确反序列化。即,反序列化时,它从类定义中获取默认值。示例类:

[ProtoBuf.ProtoContract]
public class
Test
{
    [ProtoBuf.ProtoMember(1)]
    public int Field1 = -1

    [ProtoBuf.ProtoMember(2)]
    public int Field2 = -1;
}

然后运行此代码:

var test = new Test();
test.Field1 = 0;
test.Field2 = 0;
MemoryStream ms_out = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms_out, test);
ms_out.Seek(0, SeekOrigin.Begin);
var deser = ProtoBuf.Serializer.Deserialize<Test>(ms_out);

当我执行此操作时,deser 具有 Field1 = -1Field2 = 2,而不是 0。我在这里做错了什么吗?

I'm using protobuf-net r278 in C#, and I just noticed that if I have a class with an int field, the field isn't deserialized properly if it's value is set to 0. Namely, when deserialized it gets its default value from the class definition. Example class:

[ProtoBuf.ProtoContract]
public class
Test
{
    [ProtoBuf.ProtoMember(1)]
    public int Field1 = -1

    [ProtoBuf.ProtoMember(2)]
    public int Field2 = -1;
}

Then run this code:

var test = new Test();
test.Field1 = 0;
test.Field2 = 0;
MemoryStream ms_out = new MemoryStream();
ProtoBuf.Serializer.Serialize(ms_out, test);
ms_out.Seek(0, SeekOrigin.Begin);
var deser = ProtoBuf.Serializer.Deserialize<Test>(ms_out);

When I do this, deser has Field1 = -1 and Field2 = 2, not 0's. Am I doing something wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靑春怀旧 2024-08-31 14:09:05

根据线路规范,有一个隐式的零默认值(可以使用 [DefaultValue(...)] 将其更改为其他值。您可以通过以下方式告诉它按照您的意愿行事在属性中设置 IsRequired = true

[ProtoBuf.ProtoMember(1, IsRequired = true)]

In line with the wire-spec, there is an implicit zero default (which can be changed to other values with [DefaultValue(...)]. You can tell it to behave itself as you want by setting IsRequired = true in the attribute:

[ProtoBuf.ProtoMember(1, IsRequired = true)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文