【问题标题】:Modeling Interfaces in ProtobufProtobuf 中的建模接口
【发布时间】:2021-02-22 08:31:13
【问题描述】:

我是 Protobuf 的新手,我知道无法在 Protobuf 中对接口实现进行建模。我们有一组现有的域对象,它们在 C# 中实现了一个通用的“IBase”接口。

一种选择是仅将 protobuf 生成的类用作 DTO,并在反序列化后将其转换为域类,但这意味着我需要创建一个单独的 DTO 类,我在 .proto 中使用并将其转换为域反序列化后的类

我想在 proto 中对 DerivedProduct 类进行建模,并分别在 C#Java 中生成客户端和服务器类。请就建模现有接口实现的最佳实践提供建议,如下所示。我在下面提供了一个简单的表示。

interface IBase  
{  
    string ProductName {get;set;}  
    void Add(string baseProduct);  
}

interface IDerived: IBase  
{                                 
    double ProductRate {get;set;}  
}

class DerivedProduct : IDerived      
{
    string ProductName {get;set;}  
    void Add(string baseProduct){ }  
    double ProductRate {get;set;}  
}

【问题讨论】:

  • 请阅读formatting help 了解如何包含代码块的示例。我现在已经解决了这个问题,但它会帮助你解决以后的问题。
  • 请注意,C# 和 Java 的答案可能不同。

标签: java c# protocol-buffers proto


【解决方案1】:

我不知道 Java 的情况,但在 C# 中,protoc 插件生成的类是部分类。因此,您可以将原型建模为:

message DerivedProduct {
    string product_name = 1;
    double product_rate = 2;
}

运行 protoc 生成代码,然后手动添加另一个分部类:

public partial class DerivedProduct : IDerived
{
    // The properties will already be generated by protoc in another file

    public void Add(string baseProduct)
    {
        // Implementation here
    }
}

【讨论】:

  • 感谢乔恩的回复!我会记下以后的代码格式。
猜你喜欢
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2017-03-24
  • 2021-12-03
  • 2012-01-11
  • 1970-01-01
相关资源
最近更新 更多