How to add an optional field to a class manually in protobuf-net

In my .proto, I have messages with optional fields. There is no native protogen for Debian, so I don’t need to experiment (too lazy to compile it myself :).

Could you tell me how to implement an optional field in a class in C #? I would like to have a function or something else that defines a field (in C ++, I have something like hasfoo ()). The examples I found on the Internet are nothing like this.

+4
source share
1 answer

It supports several templates here to help migrate from other serializers. Note that in protobuf-net protogen there are options to enable these elements for you automatically.

First, nothing is null ; this includes both null references and Nullable<T> for structures. So:

 [ProtoMember(1)] public int? A {get;set;} 

will behave.

Another option is the default values; using .NET conventions:

 [ProtoMember(2), DefaultValue(17)] public int B {get;set;} 

no 17 values ​​will be serialized.

For more explicit control, the ShouldSerialize* pattern (from XmlSerializer ) and the *Specified pattern (from DataContractSerializer ) are observed, so you can do:

 [ProtoMember(3)] public string C {get;set;} public bool ShouldSerializeC() { /* return true to serialize */ } 

and

 [ProtoMember(4)] public string D {get;set;} public bool DSpecified {get;set;} /* return true to serialize */ 

They can be public or private (unless you create a separate serialization assembly that requires public access).

If your main classes come from gen code, then the partial class is the ideal extension point, i.e.

 partial class SomeType { /* extra stuff here */ } 

as you can add this to a separate code file.

+5
source

All Articles