如何在 C# 中使用 MsgPack 序列化子类型

How to serialize subtypes with MsgPack in C#

我有一个关于 c# 中的 msgpack 序列化的问题。 我有一个 base class 和一个从 base 派生的 class ,它们每个都有属性,例如:

class Base
{
    int PropertyA { get; set; }
}

class DerivedFromBase : Base
{
    int PropertyB { get; set; }
}

另外我还有第三个 class 容器的对象,例如:

class Container 
{
    Base ContainerProperty { get; set; }
}

我的问题是,如果 ContainerProperty 是 DerivedFromBase 类型,MsgPack 只序列化 PropertyA,而不是 PropertyB!我怎样才能实现 MsgPack 在内部将 ContainerProperty 识别为 DerivedFromBase?我必须编写自定义序列化程序还是有 "builtin" 方式?

谢谢。

使用属性MessagePackRuntimeType让MsgPack在运行时分析类型进行序列化:

class Container 
{
    [MessagePackRuntimeType]
    Base ContainerProperty { get; set; }
}

有关详细信息,请参阅 msgpack-cli 关于多态性的文档