Mimic ProtoEnumAttribute with ProtoBuf.Meta interface

In protobuf-net, you can override the wire format for enumerations using ProtoEnumAttribute as follows:

 [ProtoContract] enum MyEnum { [ProtoEnum(Value=1)] Default, [ProtoEnum(Value=10)] Foo } 

With these attributes, where Default will usually serialize to 0 and Foo to 1 , they will now serialize to 1 and 10 respectively.

What I'm trying to do is to imitate this behavior using interfaces in ProtoBuf.Meta , so I don't need to comment on the enumerations (because I usually don't control them in my project).

Digging through the protobuf-net source, I managed to get the following (simplified) action:

 var model = RuntimeTypeModel.Create(); var meta = model.Add(enumType, applyDefaultBehaviour: true); var fields = meta.GetFields(); // Oh god why var fieldNumber = typeof(ValueMember).GetField( "fieldNumber", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic ); List<string> ordered = GetDesiredEnumOrder(enumType); int equiv = 0; foreach (var val in ordered) { var field = fields.Single(f => f.Name == val); fieldNumber.SetValue(field, equiv); equiv++; } 

However, I cannot send this, relying on a reflection in a private (read-only!) Field that just requires trouble.

So, is there a way to override enumeration posting values ​​at runtime in protobuf-net?

+3
source share
1 answer

I'm not on a PC to check this out, so you have to fix me if I'm crazy, but it should be something like (at the beginning of the application):

 RuntimeTypeModel.Default.Add(typeof(MyEnum), false) .Add(1, "Default").Add(10, "Foo"); 

The first line proposes to add a new Type to the model, without ( false ), applying any usual rules; the second line adds 2 members to the representation of this type with the required values.

If this does not work (and I will try to check later today), let me know and I will make it work (or provide an equivalent API). It just might be that this script is just not suitable for me to test it when working without attributes.

+2
source

All Articles