You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Protobuf-net多层继承序列化异常:如何实现多级继承类序列化?

Protobuf-net多层继承序列化解决方案
  • 问题根源:你把跨层子类Test3直接注册在顶层基类Test的ProtoInclude里,但Test3实际继承自Test2而非Test,protobuf-net没法识别这种跨层的继承映射,所以抛出错误:

    Unexpected sub-type: WinFormsApp1.Test3

  • 解决规则:protobuf-net要求每层基类都得显式声明自己的直接子类,继承链上每一级都要配置对应的ProtoInclude属性,不能跨层跳级注册。

修改后的代码示例:

// 顶层基类Test:仅声明直接子类Test2、Test4
[ProtoContract, ProtoInclude(1, typeof(Test2)), ProtoInclude(3, typeof(Test4))]
public class Test
{
}

// 中间类Test2:声明自己的直接子类Test3
[ProtoContract, ProtoInclude(2, typeof(Test3))]
public class Test2 : Test
{
}

// 子类Test3:继承自Test2,只需标记ProtoContract
[ProtoContract]
public class Test3 : Test2
{
}

// 子类Test4:直接继承Test,标记ProtoContract
[ProtoContract]
public class Test4 : Test
{
}

这样配置后,Test → Test2 → Test3的继承关系就能被protobuf-net正确解析,序列化包含Test、Test2、Test3、Test4的List<Test>集合时就不会再出现类型识别错误。

内容的提问来源于stack exchange,提问作者user17946664

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.01 21:54:53