使用协议缓冲区创建通用反序列化程序

Make a generic deserializer with protocol buffer

本文关键字:反序列化 程序 缓冲区 协议 创建      更新时间:2023-10-16

我正在使用 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中返回的消息将是FooBar等 - 视情况而定。因此,如果你在OuterMessage上有一个virtual(或abstract(方法,你可以使用多毛病来调用适当的方法:

var obj = Serializer.Deserialize<OuterMessage>(data); // obj could be Foo/Bar/etc
obj.DoTheThing(); // your virtual method