在我的.proto中,我有一些包含可选字段的消息.Debian没有本机原型,所以我没有一个可以试验(懒得自己编译:).
你能告诉我如何在C#中的类中实现可选字段吗?我想有一个函数或任何设置字段的idicate(在C++中我有像hasfoo()).在我在互联网上发现的例子中,没有类似的东西.
它支持许多模式,以帮助从其他序列化器转换.请注意,protobuf-net中有一些选项protogen
可以自动包含此类成员.
首先,null
省略任何事情; 这包括null
引用和Nullable<T>
结构.所以:
[ProtoMember(1)]
public int? A {get;set;}
Run Code Online (Sandbox Code Playgroud)
会表现出来.
另一种选择是默认值; 使用.NET约定:
[ProtoMember(2), DefaultValue(17)]
public int B {get;set;}
Run Code Online (Sandbox Code Playgroud)
没有值17将被序列化.
为了更明确地控制,观察ShouldSerialize*
模式(从XmlSerializer
)和*Specified
模式(从DataContractSerializer
),因此您可以:
[ProtoMember(3)]
public string C {get;set;}
public bool ShouldSerializeC() { /* return true to serialize */ }
Run Code Online (Sandbox Code Playgroud)
和
[ProtoMember(4)]
public string D {get;set;}
public bool DSpecified {get;set;} /* return true to serialize */
Run Code Online (Sandbox Code Playgroud)
这些可以是公共的或私有的(除非您生成一个需要公共的独立序列化程序集).
如果你的主要类来自代码,那么a partial class
是一个理想的扩展点,即
partial class SomeType {
/* extra stuff here */
}
Run Code Online (Sandbox Code Playgroud)
因为您可以在单独的代码文件中添加它.