如何在 protobuf-net 中手动向类添加可选字段

发布于 2024-11-15 20:54:48 字数 181 浏览 2 评论 0原文

在我的 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記柔刀 2024-11-22 20:54:48

它在这里支持多种模式,以帮助从其他序列化器进行转换。请注意,protobuf-net protogen 中有一些选项可以自动为您包含此类成员。

首先,任何 null 都被省略;这包括 null 引用和结构的 Nullable 。所以:

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

会表现。

另一个选项是默认值;使用 .NET 约定:

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

不会序列化 17 的值。

为了进行更明确的控制,可以使用 ShouldSerialize* 模式(来自 XmlSerializer)和 *Specified 模式(来自 DataContractSerializer)被观察到,所以你可以这样做:

[ProtoMember(3)]
public string C {get;set;}

public bool ShouldSerializeC() { /* return true to serialize */ }

并且

[ProtoMember(4)]
public string D {get;set;}

public bool DSpecified {get;set;} /* return true to serialize */

这些可以是公共的或私有的(除非你正在生成一个独立的序列化程序集,这需要公共)。

如果您的主类来自 code-gen,那么 partial class 是一个理想的扩展点,即

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

因为您可以将其添加到单独的代码文件中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文