如何将 C# 中现有的 POCO 类转换为 google Protobuf 标准 POCO [英] How to convert existing POCO classes in C# to google Protobuf standard POCO

查看:38
本文介绍了如何将 C# 中现有的 POCO 类转换为 google Protobuf 标准 POCO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 POCO 类,我使用 NewtonSoft json 进行序列化.现在我想将它迁移到 Google 协议爱好者.有什么方法可以迁移我的所有类(不是手动),以便我可以使用谷歌协议 buff 进行序列化和反序列化.

I have POCO classes , I use NewtonSoft json for seralization. Now i want to migrate it to Google protocol buff. Is there any way i can migrate all my classes (not manually) so that i can use google protocol buff for serialization and deseralization.

推荐答案

你只是想让它工作吗?绝对最简单的方法是使用 protobuf-net 并添加 [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)].它的作用是告诉 protobuf-net 组成字段编号,它通过获取所有公共成员,按字母顺序对它们进行排序,然后向上计数来完成.然后您可以将您的类型与 ProtoBuf.Serializer 一起使用,并且它应该按照您期望的方式运行.

Do you just want it to work? The absolute simplest way to do this would be to use protobuf-net and add [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]. What this does is tell protobuf-net to make up the field numbers, which it does by taking all the public members, sorting them alphabetically, and just counting upwards. Then you can use your type with ProtoBuf.Serializer and it should behave in the way you expect.

简单,但不是很健壮.如果您添加、删除或重命名成员,它们都可能不同步.这里的问题是协议缓冲区格式不包括名称 - 只是字段编号,随着时间的推移,保证数字变得更加困难.如果您的类型可能会改变,您可能希望明确定义字段编号.例如:

This is simple, but it isn't very robust. If you add, remove or rename members it can all get out of sync. The problem here is that the protocol buffers format doesn't include names - just field numbers, and it is much harder to guarantee numbers over time. If your type is likely to change, you probably want to define field numbers explicitly. For example:

[ProtoContract]
public class Foo {
    [ProtoMember(1)]
    public int Id {get;set;}

    [ProtoMember(2)]
    public List<string> Names {get;} = new List<string>();
}

需要注意的另一件事是非零默认值.默认情况下,protobuf-net 假定某些关于隐式默认值的事情.如果您经常使用非零默认值 并没有非常小心地这样做,protobuf-net 可能会误解您.如果您愿意,可以全局关闭它:

One other thing to watch out for would be non-zero default values. By default protobuf-net assumes certain things about implicit default values. If you are routinely using non-zero default values without doing it very carefully, protobuf-net may misunderstand you. You can turn that off globally if you desire:

RuntimeTypeModel.Default.UseImplicitZeroDefaults = false;

这篇关于如何将 C# 中现有的 POCO 类转换为 google Protobuf 标准 POCO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆