【问题标题】:How to represent interface implementation in proto file如何在 proto 文件中表示接口实现
【发布时间】:2018-08-01 07:29:49
【问题描述】:

我正在使用 protogen 工具从 .proto 文件生成 c# 类。我想知道是否有可能在原型文件中表示接口实现。例如,有什么方法可以在 proto 文件中表示下面的内容。

interface ILog
{

}

class ConsoleLog: ILog
{

}

【问题讨论】:

    标签: protocol-buffers protobuf-net


    【解决方案1】:

    .proto 没有接口的概念,除非你计算服务(反正 protogen 不涉及)。

    如果您想在本地添加一些东西,代码都是 C#,但是我的建议是为此简单地使用“部分类”,并在另一个代码文件中添加所有接口方面。 Protogen 总是发出部分类。

    【讨论】:

    • 感谢您的快速答复。我会试一试的。
    • 曾经有过一些做接口的想法,但最终都变成了Messages被封装在其他消息中。如果有 20 多条消息交错,则会造成混乱。
    • @MarkoBencik 当前的 protogen 从不发射接口;接口不是 .proto 处理的概念; protobuf-net 对通过接口序列化数据的支持有限,但听起来你犯了一个经典的错误,即尝试序列化域模型,而不是创建一个合适的 DTO 模型针对目标序列化平台
    • 公平地说,我并没有积极地使用 protobuf-net,我正在使用 C++,但这应该不会有很大的不同。现在 DTO 是一种解释,大多数人都做错了。我不确定我是否和你有同样的理解。我认为您的意思是类分解模型,如果是的话,请看他的喜好。 github.com/OpenSimulationInterface/open-simulation-interface/… 这是我正在使用的。在这里,您将看到域模型被拉入 protobuf。
    【解决方案2】:

    TL;DR - 创建事件包装器

    这有点晚了,但我想我会发布一个想法。这不是在 .proto 文件上创建接口的用例 - 只是我认为与这篇文章相关的问题的解决方案(我最初的想法相同)。我想处理通用事件,但这些事件与原型生成的类相关。

    TempEvent.proto

    message TempEvent {
        int32 deviceId = 1;
        float humidity = 2;
        float temperature = 3;
    }
    

    从事件队列中获取的消费者类(传感器读数):

    Service service;
    
    TempEvent event = queue.remove();
    ((EventService)service).process(new EventWrapper(event));
    

    一旦数据被反序列化,只需创建一个实现事件的简单包装器。

    public interface Event<T> {
        T getEvent();
    }
    
    public class EventWrapper<T> implements Event {
        private T event;
    
        public EventWrapper(T eventType) {
            this.event = eventType;
        }
    
        public T getEvent() {
            return this.event;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2019-06-13
      • 1970-01-01
      • 2020-04-30
      • 2010-10-16
      • 2011-01-08
      相关资源
      最近更新 更多