How do I generate a .proto file from a C# class decorated with attributes?

前端 未结 2 1391
我寻月下人不归
我寻月下人不归 2020-12-05 07:07

Trying to get my mind around google protobuf. I found some implementation of protobuf in C# but they seems to lack one feature: the ability to generate .proto files automati

相关标签:
2条回答
  • 2020-12-05 07:15

    Before Skeet Marc runs in here and gets massive ups, let me point out protobuf.net.

    0 讨论(0)
  • 2020-12-05 07:39

    Good news; what you have described (having existing C# classes) is the expected use-case of protobuf-net. All the .proto stuff ("protogen", the VS add-in, etc) were all added as afterthoughts. The core of protobuf-net doesn't know about them or care about them.

    protocol buffers defines a DSL (.proto, as you mention) that is shared between implementations, and is (sometimes) used for code generation. When I first wrote protobuf-net, the code-generation aspect wasn't my biggest concern - simply that .NET developers are generally guilty (myself included) of "implementation first" rather than "contract first".

    As a consequence, protobuf-net doesn't need .proto files to work; an attributed class is sufficient to unambiguously serialize/deserialize. Just use Serializer.Serialize , .Merge and .Deserialize (etc).

    That said; it does include some very under-developed and experimental support for this:

    string proto = Serializer.GetProto<YourType>();
    

    This is far from complete, but may work for simple types. If you have some specific cases where it fails, then let me know (add a comment or log an issue). However; most of the time, people interested in .proto would write the .proto first and work from there.

    Examples of working decorated types are shown on the project home page; it is entirely up to you whether you use WCF attributes, xml attributes or protobuf-net attributes (although the latter provide more control over some specific serialization points, such as inheritance and numeric layouts).

    0 讨论(0)
提交回复
热议问题