我在 C# 和 C++ 上使用 RabbitMQ 和 Protocol Buffer 。我有 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
关于c# - 使用 Protocol Buffer 制作通用反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50829579/