【问题标题】:Serialize a class having an interface type member using protobuf-net使用 protobuf-net 序列化具有接口类型成员的类
【发布时间】:2010-09-23 23:50:40
【问题描述】:

我无法使用 protobuf-net 序列化我的类,问题似乎是 protobuf-net 无法序列化接口。

interface MyInterface
{
    string name;
}

[ProtoContract]
[ProtoInclude(1, typeof(MyClass1))]
[ProtoInclude(2, typeof(MyClass2))]
public abstract class ParentClass
{
    [ProtoMember(1)]
    List<MyInterface> elements;
}


[ProtoContract]
public class MyClass1 : ParentClass, MyInterface
{
    [ProtoMember(1)]
    int x;
}

[ProtoContract]
public class MyClass2 : MyInterface
{
    [ProtoMember(1)]
    string y;
}

我无法序列化 MyClass1 类型的任何对象,因为元素是一个接口列表,可以是 Mylass1 或 MyClass2。我收到一些编码未设置错误。

谁能告诉我如何解决这个问题。谢谢。

【问题讨论】:

  • (现在 v2 支持)

标签: c# protocol-buffers protobuf-net


【解决方案1】:

在当前的官方版本中,我不包括接口序列化支持。但是,我确实有一个补丁(来自另一个用户)似乎可以实现这一点。

我还没有将这个补丁应用到核心,只是因为我需要在添加更多功能之前先专注于完成“v2”(特别是因为该功能需要完全重新为 v2 实现),但如果您愿意,我很乐意与您分享补丁。

或者:使用基类而不是接口。 支持的(通过[ProtoInclude]) - 然而,你的MyClass1已经有一个父类的事实有点复杂。


编辑:现在 v2 支持此功能。显然,代码必须知道预期的具体实现 - 但现在可以将包含附加到接口(或可选地在原始 POCO 模型的代码中指定)。

【讨论】:

  • 如果你能分享补丁那就太好了.... 另外我想知道我是否可以用 AppFabric 插入 protobuf-net,你试过了吗?顺便说一句..这个项目做得很好!
  • @ace 给我发电子邮件(见个人资料)以获取补丁。重新 ppfabroc,不是从早期的 beta 版本开始。但是你总是可以给它一个 blob :)
【解决方案2】:

我的猜测是你需要添加:

[ProtoInclude(1, typeof(MyClass1))]
[ProtoInclude(2, typeof(MyClass2))]

到您的MyClass1MyClass2,因为您从MyInterface 继承并且序列化不会知道类型。

【讨论】:

    猜你喜欢
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多