用于 C# 的 Google Protobuf 3.0.0 程序集

Posted

技术标签:

【中文标题】用于 C# 的 Google Protobuf 3.0.0 程序集【英文标题】:Google Protobuf 3.0.0 assemblies for C# 【发布时间】:2015-08-17 11:55:29 【问题描述】:

在我们的项目中,我们成功地将 Google Protobuf 用于 C++。现在需要编译相同的 *.proto 文件以在 C# 代码中使用它。我下载了最近的Protobuf version 3.0.0-alpha-3。它为 C# 提供了对 proto2 格式的支持,这对我来说已经足够了。我可以成功构建我的 *.proto 文件并获得一个 *.cs 文件。但是,当我将生成的 *.cs 文件添加到我的 C# 项目并尝试构建时,我收到如下编译器错误:"The type or namespace name 'Google' could not be found in the global namespace (are you missing an assembly reference?)" 这是发生错误的地方:

// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: DiagramExport.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code

using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;

现在我在项目页面上的可用发布 ZIP 中找不到任何 DLL 等,我可以将其作为参考包含在我的 C# 项目中。只有 protoc.exe 和一些 *.proto 文件在那里。我的简单问题是:我从哪里获得这些程序集?

(备注:我尝试按照 README 文件中的说明从源代码构建项目protobuf-csharp-3.0.0-alpha-3,但未能使用“开箱即用”的 Visual Studio 2013 Update 4 构建它;我收到了一些编译器错误.)

【问题讨论】:

我不知道您要使用的库是什么,但我会以protobuf.net 开头。 @Sinatr 据我了解,我尝试使用 Google 的“官方”发行版。至少,谷歌网站上的文档指向这个项目(参见developers.google.com/protocol-buffers)我不想使用 protobuf.net,因为我们已经使用 protoc.exe 为 C++ 和 Java 编译了 *.proto 文件。 Google 与 .Net 无关。所以有人必须做一项肮脏的工作,将包装器移植到 c++ 库或将源代码移植到 c#。我在链接页面上没有看到c#。只需在 C# 代码中使用 protobuf.net。 @Sinatr:你错了。 Google 已将 Jon Skeet 的 Protobuf C# 实现纳入官方 Protobuf Github 存储库。 github.com/google/protobuf/tree/master/csharp Marc 的实现历来更受欢迎,但 Jon 的实现更类似于 Google 的 Java 实现。 (而 Jon 是 Google 员工等) @KentonVarda,我再说一遍,Google 与 .Net(由 MS 制作和支持)无关。他们可以(理论上,有一天)添加 c# 支持,但他们不必,这是我的观点。我知道 protobuf 有很多实现,但我们谈论的是你想在生产中使用的一种,对吧?你读过你链接的页面吗? P.s.:具有讽刺意味的是,我使用谷歌查找 protobuf.net,但我没能很快找到 Jon 的,所以我只是编辑评论并只留下 protobuf.net 链接。 【参考方案1】:

阅读this 和this 文档页面后,我发现可以通过在包管理器控制台中执行以下命令来为我的项目安装Protocol Buffers NuGet 包:

Install-Package Google.ProtocolBuffers

控制台可在 Visual Studio 2013 中通过工具 --> NuGet 包管理器 --> 包管理器控制台访问。经理下载了这个包,我在我的项目中得到了两个引用“Google.ProtocolBuffers”和“Google.ProtocolBuffers.Serialization”,这让编译器很高兴。现在完美运行!

【讨论】:

仅供参考,有一点更新:Google Protocol Buffers C# 3.0.0-beta2 也可用Install-Package Google.Protobuf -Pre【参考方案2】:

查看发行说明here

C# (Beta) 部分下,您会发现:

Breaking: Preconditions is renamed to ProtoPreconditions
Breaking: GeneratedCodeInfo is renamed to GeneratedClrTypeInfo

因此,Grpc.Tools 软件包随附的 protoc.exe 似乎生成了“旧”代码。我将 protoc.exe 替换为 this 并重新编译(重新生成)我的类以解决问题。

【讨论】:

以上是关于用于 C# 的 Google Protobuf 3.0.0 程序集的主要内容,如果未能解决你的问题,请参考以下文章

google protobuf 数据类型_理解Protobuf数据格式解析

使用 C# Google.Protobuf 将 ByteString 反序列化为对象

C++ 中的 Google ProtoBuf 与 C# (UDP) 中的 Protobuf-net 聊天

C#中使用ProtoBuf提高序列化速度对比二进制序列化

Google Protobuf简明教程

Google Protobuf简明教程