protobuf.net意外的子类型

Mar*_*tin 11 .net c# protocol-buffers protobuf-net

我在使用Protobuf.net的项目中遇到此异常:

InvalidOperationException "Unexpected sub-type: foo"
Run Code Online (Sandbox Code Playgroud)

我有一个我要发送的类,如下所示:

class message
{
    list<bar> listOfBars;
}
Run Code Online (Sandbox Code Playgroud)

foo继承了bar,但是protobuf似乎对此产生了阻碍并产生了上面的异常.这有什么办法吗?我需要能够在列表中保存所有不同的bar子类型,因此更难以/不可能采用更多类型约束的解决方案.

djd*_*d87 18

我可能弄错了,但我认为你需要在继承的类上指定哪些子类继承它,例如:

[Serializable, ProtoContract, ProtoInclude(100, typeof(Foo))]
class Bar { }

[Serializable, ProtoContract]
class Foo : Bar { } // Inherits from Bar
Run Code Online (Sandbox Code Playgroud)

  • 这不违反开放原则吗?我的意思是,每次添加另一个子类时,都需要修改基类(include属性)?此外,基类和子类需要在同一个程序集中,以避免循环依赖.这还有另一种方式吗?也许手动设置protobuf模型(任何文档)? (6认同)
  • @AntonioNakicAlfirevic:我相信你已经发现了这一点,但对于遇到这个问题的其他人:http://stackoverflow.com/questions/6247513/protobuf-net-inheritance (4认同)