一般使用Protobuf的步骤为linux
.proto
文件protoc
生成对应语言的代码以生成C#代码为例,使用以下命令:shell
protoc -I ../protos --csharp_out ../Generated --grpc_out ../Generated \ --plugin=protoc-gen-grpc=grpc_csharp_plugin ../protos/ExportOffice.proto
其生成的C#代码像这样:bash
public const int TemplatePathFieldNumber = 1; private string templatePath_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TemplatePath { get { return templatePath_; } set { templatePath_ = pb::ProtoPreconditions.CheckNotNull(value, value") } }
C#开发一般使用Pascal、Camel二种命名规范工具
上面代码中成员变量 templatePath_
应该是 Camel
命名规则,但 Camel
命名规则没有以_结尾的。code
个人项目中为规范化代码我使用了 StyleCop
自动代码审查工具,它会将不符合命名规范的代码视为编译错误,这种命名的代码是编译不过的,而且 StyleCop
并无提供忽略指定类文件的功能,只能改代码使其符合命名规范了。事件
代码是自动生成的手动确定确定不现实的,那么就自动改。能够用正匹配到这种命名的变量而后替换便可,因而我写了个shell脚本能够作这件事,代码以下:ip
#!/usr/bin/env bash #Usage: xxx.sh TOOLS_DIR=/mnt/d/Program_Code/Package/gRPC/Tools/linux_x64 BASH_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" cd $BASH_DIR rm ../Generated/*.cs $TOOLS_DIR/protoc -I ../protos --csharp_out ../Generated --grpc_out ../Generated \ --plugin=protoc-gen-grpc=$TOOLS_DIR/grpc_csharp_plugin ../protos/ExportOffice.proto sed -ri -e 's/\b([a-zA-Z0-9_]+)_\b/_\1/g' \ -e 's/\b(descriptor)\b/_\1/g' \ -e '1s/^/\xef\xbb\xbf/' ../Generated/*.cs
这个脚本作了3件事开发
使用时须要将 TOOLS_DIR
变量修改成 protoc
所在目录rpc