代码之家  ›  专栏  ›  技术社区  ›  ace

使用protobuf net序列化具有接口类型成员的类

  •  2
  • ace  · 技术社区  · 14 年前

    我无法使用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类型的任何对象,因为元素是接口列表,可以是MyClass1或MyClass2。我收到一些编码未设置错误。

    有人能告诉我怎么解决这个问题吗?谢谢。

    2 回复  |  直到 13 年前
        1
  •  1
  •   Marc Gravell    13 年前

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

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

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


    编辑:现在V2支持此功能。显然,代码必须知道预期的具体实现,但是include现在可以附加到接口上(或者可以在普通POCO模型的代码中指定)。

        2
  •  0
  •   SwDevMan81    14 年前

    我猜你需要补充:

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

    对你们两个 MyClass1 MyClass2 因为你继承自 MyInterface 而序列化将不知道类型。