protobuf-net enum serialization

岁酱吖の 提交于 2019-12-04 16:39:56

问题


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: Only data-contract classes (and lists/arrays of such) can be processed"


回答1:


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: add an enum with value 0 (since 0 is always the CLI default value for zeros), for example

public enum SiteType
{
    Error = 0,
    ...

2: tell it which value to use by default:

[ProtoMember(10), DefaultValue(SiteType.Partition)]
public SiteType Type { get; set; }

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; }



回答2:


Sample:

[DataContract]
[ProtoContract]
public enum SiteType
{
    [EnumMember]
    [ProtoEnum]
    Site = 1,
    [EnumMember]
    [ProtoEnum]
    Partition = 2,
    [EnumMember]
    [ProtoEnum]
    Module = 3
}

[DataContract]
[Serializable]
[ProtoContract]
public class SiteDTO
{
    [DataMember]
    [ProtoMember(1)]
    public int Id { get; set; }
    ...
    [DataMember]
    [ProtoMember(10)]
    public SiteType Type { get; set; }
}


来源:https://stackoverflow.com/questions/4135569/protobuf-net-enum-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!