【问题标题】:How to find what message I just deserialized with protobuf-net?如何找到我刚刚用 protobuf-net 反序列化的消息?
【发布时间】:2012-08-28 13:16:53
【问题描述】:

一段时间以来,我一直很高兴地在我的一些 C++ 应用程序之间使用 protobuf+ZeroMQ。我需要编写一个 C# 应用程序。我已经让 Protobuf-NET 工作了,我相信我终于弄清楚了如何从 ZeroMQ 消息中反序列化,但我一辈子都无法弄清楚如何查看反序列化数据中的消息。 在我的 C++ 应用程序中,我将反序列化为一个类,并且我能够简单地执行以下操作:

if(msg.has_msgTypeX())
    blah

我不知道如何在 Protobuf-NET 中做到这一点。

示例 .proto 文件:

package Messaging;

message Message {
    optional string uuid                = 1;

    optional Map map                = 2;
    optional Block block                = 3;
    optional Tile tile              = 4;
}

message Map {
    repeated Block block        = 1;
}

message Block {
    repeated Tile   tile            = 1;
    required int32 zCoord           = 2;
    required int32 version          = 3;
}

message Tile {
    required int32 xGCoord          = 1;
    required int32 yGCoord          = 2;
    required int32 zGCoord          = 3;
}

使用它来反序列化:

Messaging.Message msg = ProtoBuf.Serializer.Deserialize<Messaging.Message>(new MemoryStream(zmqMsg.Body));

从这里到哪里?如何判断消息是否包含 Tile、Block 或 Map 消息?

【问题讨论】:

    标签: c# protobuf-net


    【解决方案1】:

    怎么样:

    if(msg.map != null) {
        // ...
    }
    
    if(msg.block != null) {
        // ...
    }
    
    if(msg.tile != null) {
        // ...
    }
    

    ?实际上,如果这些选项是互斥的,那么这种情况也可以通过继承在 protobuf-net 中建模(对于相同的布局)——但是,由于 .proto 没有相应的语法,因此您必须手动处理。

    【讨论】:

    • 我收到一个意外的符号错误!。你能解释一下实现相同布局的继承过程吗?昨晚我花了很多时间阅读这方面的内容,但无法弄清楚 Protobuf-NET 的真正工作原理,因为我是 C# 新手(我来自 C++)。
    • @S.Richmond 道歉;我的手机肯定吃了=... 修复
    • 很好,谢谢。问题得到了回答。这是使用 protobuf-NET 的正确方法吗?
    • @S.Richmond 这是使用 protobuf-net 的完美有效方式,特别是如果您从预先存在的 .proto 定义开始;不过,protobuf-net 并不要求你使用它——你也可以从代码优先开始,即只拥有你的 DTO 类并且看不到 .proto。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2012-12-19
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多