Error while using ProtoBuf-Net with flags enum

核能气质少年 提交于 2019-12-19 07:35:54

问题


While using ProtoBuf-Net and serializing an enum property, where the enum is set to [FlagsAttribute], I received the following error message when serializing an enum value composed of multiple flags.

The error is: The value (MyEnum.MyValue) has no wire-representation for property MyProperty

Where MyEnum is:

[Flags]
public Enum MyEnum
{
    MyValue = 0,
    MyValue1 = 1,
    MyValue2 = 2,
    MyValue4 = 4,
    MyValue8 = 8,
}

and

MyProperty = MyEnum.MyValue2 | MyEnum.MyValue4;

Seems to be a bug in protobuf-net?


回答1:


Update : this is now fixed in r274; you would use:

[ProtoMember(12, DataFormat = DataFormat.TwosComplement)]
public MyEnum MyValue {get;set;}

Ultimately the protocol buffers wire format doesn't provide any scope for [Flags] enums - it enforces enum values against the discreet set. I could allow this easily enugh, but:

  • I'd probably have to disable enum mappings in this case, or do a lot of ugly bit- matching work
  • it would not be strictly compatible

An easier way of doing this may be to do a shim in your code:

public MyEnum MyValue {get;set;}
[ProtoMember(12)]
private int MyValueWire {
    get {return (int)MyValue;}
    set {MyValue = (MyEnum)value;}
}

The other alternative would be to add a flag that works like the above on your behalf; treating it as an int rather than an enum.



来源:https://stackoverflow.com/questions/1494939/error-while-using-protobuf-net-with-flags-enum

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