A simple example
= syntax " proto3 " ; // set the default version, the default is not write proto2 // l, 2,3 Tag is a tag field does not represent the value of the field Message FirstMessage { Int32 ID = . 1 ; String name = 2 ; BOOL is_male = 3 ; }
syntax = " proto3 " ; Message the Person { Int32 ID = . 1 ; String name = 2 ; a float height = . 3 ; a float weight = . 4 ; bytes Avatar = . 5 ; String In Email = . 6 ; BOOL email_verified = . 7 ; REPEATED String PHONE_NUMBER =. 8; packed the // // represents the range of digital / field you want to keep. Can not be used on their own or other developers, is accounting for a pit Reserved 9,10,20 to 100, 200 to max; Reserved "foo", "bar" ; }
Defined message definition server and client, if a field service charge is not the end of traditional values, it will default to the default values using the following types of field
It can also be used in the enumeration reserved, repeated
The definition of an enumeration
Gender = gender . 11 ; enum Gender { of NOT_SPECIFIED for = 0 ; // must be 0 FEMALE = . 1 ; MALE = 2 ; }
Gender = gender . 11 ; enum Gender { Option allow_alias = to true ; of NOT_SPECIFIED for = 0 ; // must be 0 // two words are represented by F FEMALE = . 1 ; WOMAN = . 1 ; // two words are represented by M MAN = 2 ; MALE = 2 ; }
If too much definition in a message, it will affect the quality of reading the code can be written in the form similar to the class, you can call
Further, the message may also define message nested
= syntax " proto3 " ; Message the Person {
// use the modified repeat repeated field indicates a person can have a plurality of addresses repeated = 13 is the Address address;
// address Message the Address { String = Province. 1; String City = 2; String ZIP_CODE. 3 = ; String = Street. 4; String Number. 5 =; } }
Assume a larger project, there are exactly two message called the same name, but the directory structure is not the same, only this time by a different directory structure, can not avoid conflict, you can use the Package
In the compilation will automatically generate C # namespace namespace My.Project
package my.project;//C# namespace My.Project
You can also set the namespace
option csharp_namespace ="My.WebApis";
Set Protocol Buffers Compiler
protoc compiler is mainly used to generate code, Download
https://github.com/protocolbuffers/protobuf/releases
Find the corresponding version used here is protoc-3.11.4-win64
Decompression, find yourself a directory to store up
Set environment variables, copy the path (to the bin directory: E: \ protoc-3.11.4-win64 \ bin)
Added to the path environment variable
success
Use the command line in vscode
In the terminal input protoc, if not restart vscode, because the environment variable, vscode yet read
After entering protoc can view the parameters yourself
Used to generate C # code protoc
protoc --csharp_out=csharp date.proto