protobuf-net枚举序列化 [英] protobuf-net enum serialization
问题描述
要使用protobuf-net序列化枚举,需要做什么?序列化具有枚举属性的类时遇到以下错误,如果从属性声明中删除了DataMember属性,它会正常工作。
What needs to be done in order to serialize enums with protobuf-net? I'm getting the below error when serializing a class having an enum property, if the DataMember attribute is removed from the property declaration it works fine.
System.InvalidOperationException:只能处理数据合同类(以及此类的列表/数组
)
"System.InvalidOperationException: Only data-contract classes (and lists/arrays of such) can be processed"
推荐答案
I 怀疑实际上是两种不同的情况,但是对于安德鲁添加的代码示例,这是因为它无法(事先)弄清楚默认值的处理方式(默认情况下) ,则数据在接收方被视为可选的 )。解决此问题的方法有3种:
I suspect they are actually 2 different scenarios, but with regard to the code sample added by Andrew, this is because it can't figure out (in advance) what it is going to do with regards to default values (by default, data is treated as optional at the receiver). There are 3 ways of fixing this:
1:例如,添加一个值为0的枚举(因为0始终是CLI的默认零值),例如
1: add an enum with value 0 (since 0 is always the CLI default value for zeros), for example
public enum SiteType
{
Error = 0,
...
2:告诉它默认使用哪个值:
2: tell it which value to use by default:
[ProtoMember(10), DefaultValue(SiteType.Partition)]
public SiteType Type { get; set; }
3:告诉引擎它确实不需要担心,即是将具有一个值:
3: tell the engine that it really doesn't need to worry about it, i.e. that it is going to have a value:
[ProtoMember(10, IsRequired = true)]
public SiteType Type { get; set; }
这篇关于protobuf-net枚举序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!