使用协议缓冲区创建通用反序列化程序
Make a generic deserializer with protocol buffer
我正在使用 C# 和 C++ 上的 RabbitMQ 和协议缓冲区。我有 5 个不同的类,每个类将包含一个字段"ActionType"。根据操作类型的数量,我想调用正确的函数,但是当我从 RabbitMQ 收到消息时,我不知道当我想反序列化消息时,消息属于哪个类。有没有办法将消息反序列化/转换为通用对象,或者我只能从操作类型中获取值,然后反序列化消息?
用protobuf术语来说,这听起来像是一个oneof
场景,有5个子消息。oneof
将为您提供一个鉴别枚举和 5 条消息。意义:
message OuterMesage {
oneof actionType {
Foo foo = 1;
Bar bar = 2;
...
}
}
message Foo {...}
message Bar {...}
...
您将数据反序列化为OuterMesage
,并通过.actionTypeCase
(通常在switch
中(检查要查看哪些.foo
/.bar
等。
请注意,如果您使用的是protobuf-net,则可以将完全相同的场景建模为继承,从而允许使用多态性;即
[ProtoContract]
[ProtoInclude(1, typeof(Foo)]
[ProtoInclude(2, typeof(Bar)]
public class OuterMessage { ... }
[ProtoContract]
public class Foo : OuterMessage {}
[ProtoContract]
public class Bar : OuterMessage {}
这实际上是完全相同的数据布局,只是现在您从反序列化OuterMessage
中返回的消息将是Foo
、Bar
等 - 视情况而定。因此,如果你在OuterMessage
上有一个virtual
(或abstract
(方法,你可以使用多毛病来调用适当的方法:
var obj = Serializer.Deserialize<OuterMessage>(data); // obj could be Foo/Bar/etc
obj.DoTheThing(); // your virtual method
相关文章:
- 如何知道QDataStream不能反序列化某些内容
- 增强基于 XML class_id的反序列化
- 提升反序列化对象具有 nan 或 -nan 值
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 如何反序列化数组?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 通过 tcp 发送 C# 类并在 C++ 上反序列化
- 序列化和反序列化boost共享指针
- 在C++中使用POCO和grain对多个对象进行反序列化
- C++中整数向量的序列化/反序列化
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 使用 QDataStream 对原始数据进行反序列化
- 使用协议缓冲区创建通用反序列化程序
- 如何在C++中从头开始反序列化文件(没有库)
- 在协议缓冲区 c++ 中反序列化字符串数组
- 在进程的内存中序列化/反序列化
- 谷物/C++ 11 - 如何指定反序列化的可选参数
- 关于反序列化程序 pop 函数的模板化专用化的歧义
- c++反序列化通过UDP从c#应用程序发送的对象
- C++json反序列化程序