c# - 从多个 .proto 文件创建一个 .proto 文件

标签 c# protocol-buffers protobuf-net

我们一直在使用Serializer.GetProto<T>()为十几条消息生成原始定义。我们希望将所有定义合并到一个 .proto 文件中,以便更轻松地查看我们正在发送的消息。但是我找不到合并输出的方法。最大的问题是当一个 POCO 在多个消息中使用时(例如下面示例中的 Person)。有没有办法将多个 .proto 定义合并为一个定义?

或者是Serializer.GetProto<T>()用于这项工作的工具是错误的,而其他工具已经可以做到这一点?

使用 protobuf-net v2.0.0.668。


最小示例(摘要:类 DepartmentOrder 都包含类 Person ,为 DepartmentOrder 生成原型(prototype)定义):

class Program
{
  public static void Main(string[] args)
  {
    string departmentProto = Serializer.GetProto<Department>();
    string orderProto = Serializer.GetProto<Order>();

    Console.WriteLine(departmentProto);
    Console.WriteLine(orderProto);
    Console.ReadKey();
  }
}

[DataContract]
public class Person
{
  [DataMember(Order = 1)]
  public string FirstName { get; set; }

  [DataMember(Order = 2)]
  public string LastName { get; set; }
}

[DataContract]
public class Department
{
  [DataMember(Order = 1)]
  public string Name { get; set; }

  [DataMember(Order = 2)]
  public Person[] Employees { get; set; }
}

[DataContract]
public class Order
{
  [DataMember(Order = 1)]
  public string ItemOrdered { get; set; }

  [DataMember(Order = 2)]
  public Person Customer { get; set; }
}

实际输出:

package ConsoleApplication1;
message Department {
  optional string Name = 1;
  repeated Person Employees = 2;
}
message Person {
  optional string FirstName = 1;
  repeated string LastName = 2;
}

package ConsoleApplication1;
message Order {
  optional string ItemOrdered = 1;
  repeated Person Customer = 2;
}
message Person {                  <-- Person is repeated
  optional string FirstName = 1;
  repeated string LastName = 2;
}

期望的输出:

package ConsoleApplication1;
message Department {
  optional string Name = 1;
  repeated Person Employees = 2;
}
message Order {
  optional string ItemOrdered = 1;
  repeated Person Customer = 2;
}
message Person {                  <-- Person only appears once
  optional string FirstName = 1;
  repeated string LastName = 2;
}

最佳答案

GetProto() 假设您的模型将具有一个涉及您需要的所有内容的根类型。如果没有,您可以发明一个假类型,其中包含您关心的所有类型作为属性。即使您从未使用过它,也可以在 GetProto() 中使用该类型来获取复合模型文件。并不理想,但其他选项是:

  • 手动合并
  • 更改代码

关于c# - 从多个 .proto 文件创建一个 .proto 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27549313/

相关文章:

c# - Visual Studio - 如何在调试器中更改方法的返回值?

c# - 在 Visual Studio 中调试时激活自定义新窗口

windows - Windows 上运行的 C# 与 linux 上运行的 C 通过 protobuf 进行通信

java - 如何在 Java 代码和 .proto 文件之间共享 Enum 值

arrays - 如何将 JSON 数组建模为 protobuf 定义

c# - 意外的 protobuf-net 序列化程序行为

c# - SslStream错误: Stream was not writable

C# 语法解释

c# - 使用 protobuf-net 生成 C# 时保留 proto 注释

c# - 具有 ProtoBuf.Meta 接口(interface)的模仿 ProtoEnumAttribute