how to add optional field to a class manually in protobuf-net
In my .proto I have some messages that have optional fields. There is no native protogen for Debian so I don't have one to experiment with (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 whatever that idicate the field is set (in C++ I ha开发者_StackOverflow中文版ve something like hasfoo() ). In examples I found in the internet there is nothing like that.
It supports a number of patterns here, to help transition from other serializers. And note that there are options in the protobuf-net protogen
to include such members for you automatically.
Firstly, anything null
is omitted; this includes both null
references and Nullable<T>
for structs. So:
[ProtoMember(1)]
public int? A {get;set;}
will behave.
Another option is default values; using .NET conventions:
[ProtoMember(2), DefaultValue(17)]
public int B {get;set;}
no values of 17 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 */
These can be public or private (unless you are generating a standalone serialization assembly, which requires public).
If your main classes are coming from code-gen, then a partial class
is an ideal extension point, i.e.
partial class SomeType {
/* extra stuff here */
}
since you can add that in a separate code file.
精彩评论