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

标签 c# msgpack

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

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

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

此外,我还有一个第三类容器的对象,例如:

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

我的问题是,如果 ContainerProperty 的类型为 DerivedFromBase,MsgPack 仅序列化 PropertyA,而不序列化 PropertyB!我怎样才能实现 MsgPack 在内部将 ContainerProperty 识别为 DerivedFromBase?我是否必须编写自定义序列化器或者是否有“内置”方式?

谢谢。

最佳答案

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

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

有关更多详细信息,请参阅 msgpack-cli documentation on polymorphism

关于c# - 如何在 C# 中使用 MsgPack 序列化子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045890/

相关文章:

c++ - msgpack 的 object_with_zone 有什么作用?

c# - 在 MessagePack 中将具有接口(interface)作为属性类型的对象序列化

c# - 使用 C# 连接到 PowerPivot

c# - 站点地图不显示为 xml

golang msgpack 自定义编码

java - MsgPack第三方对象序列化

objective-c - Objective-C 的 MessagePack 实现

c# - Winforms 文本框 - 使用 Ctrl-Backspace 删除整个单词

C# MVC foreach循环问题

c# - 使用 Assembly.ReflectionOnlyLoadFrom 加载 WPF 项目引用的程序集时出现奇怪的 FileLoadException