【问题标题】:How to serialize subtypes with MsgPack in C#如何在 C# 中使用 MsgPack 序列化子类型
【发布时间】:2017-03-27 12:02:52
【问题描述】:

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

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

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

另外我还有一个第三类Container的对象,例如:

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

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

谢谢。

【问题讨论】:

    标签: c# msgpack


    【解决方案1】:

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

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

    更多详情,请查看msgpack-cli documentation on polymorphism

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多