


































通常使用Protobuf的步骤为
.proto 文件protoc 生成对应语言的代码以生成C#代码为例,使用如下命令:
protoc -I ../protos --csharp_out ../Generated --grpc_out ../Generated \
--plugin=protoc-gen-grpc=grpc_csharp_plugin ../protos/ExportOffice.proto
其生成的C#代码像这样:
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 命名规则没有以_结尾的。
我的项目中为规范化代码我使用了 StyleCop 自动代码审查工具,它会将不符合命名规范的代码视为编译错误,这种命名的代码是编译不过的,并且 StyleCop 并没有提供忽略指定类文件的功能,只能改代码使其符合命名规范了。
代码是自动生成的手动肯定肯定不现实的,那么就自动改。可以用正匹配到这种命名的变量然后替换即可,于是我写了个shell脚本可以做这件事,代码如下:
#!/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 所在目录
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。