protobuf-net 未反序列化 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 = -1
和 Field2 = 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据线路规范,有一个隐式的零默认值(可以使用
[DefaultValue(...)]
将其更改为其他值。您可以通过以下方式告诉它按照您的意愿行事在属性中设置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 settingIsRequired = true
in the attribute: