如何在 protobuf-net 中手动向类添加可选字段
在我的 .proto 中,我有一些带有可选字段的消息。 Debian 没有原生的 protogen,所以我没有可以尝试的(懒得自己编译它:)。
你能告诉我如何在 C# 中的类中实现可选字段吗?我想要一个函数或任何指示该字段已设置的东西(在 C++ 中我有类似 hasfoo() 的东西)。在我在互联网上找到的示例中,没有类似的内容。
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 have something like hasfoo() ). In examples I found in the internet there is nothing like that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它在这里支持多种模式,以帮助从其他序列化器进行转换。请注意,protobuf-net
protogen
中有一些选项可以自动为您包含此类成员。首先,任何
null
都被省略;这包括null
引用和结构的Nullable
。所以:会表现。
另一个选项是默认值;使用 .NET 约定:
不会序列化 17 的值。
为了进行更明确的控制,可以使用
ShouldSerialize*
模式(来自XmlSerializer
)和*Specified
模式(来自DataContractSerializer
)被观察到,所以你可以这样做:并且
这些可以是公共的或私有的(除非你正在生成一个独立的序列化程序集,这需要公共)。
如果您的主类来自 code-gen,那么
partial class
是一个理想的扩展点,即因为您可以将其添加到单独的代码文件中。
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 bothnull
references andNullable<T>
for structs. So:will behave.
Another option is default values; using .NET conventions:
no values of 17 will be serialized.
For more explicit control, the
ShouldSerialize*
pattern (fromXmlSerializer
) and the*Specified
pattern (fromDataContractSerializer
) are observed, so you can do:and
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.since you can add that in a separate code file.