【问题标题】:Protobuf.net: how to handle inheritance without [ProtoInclude]Protobuf.net:如何在没有 [ProtoInclude] 的情况下处理继承
【发布时间】:2012-08-05 20:31:30
【问题描述】:

我正在使用 Protobuf.net 序列化一些类。我希望能够序列化 SuperHero 类(如下),而不必在基类上指定 [ProtoInclude]。这是因为派生类是自动生成的,而基类不是,所以基类并不直接知道它的派生类。

    [ProtoContract]
    class Person
    {
        [ProtoMember(1)]
        public int Id { get; set; }
        [ProtoMember(2)]
        public string Name { get; set; }
    }

    [ProtoContract]
    class SuperHero : Person
    {
        [ProtoMember(3)]
        public string Powers { get; set; }
    }

我使用的是最新版本的 protobuf.net。

【问题讨论】:

    标签: c# serialization protocol-buffers protobuf-net


    【解决方案1】:

    首先要注意:在某些时候,您的代码必须知道子类 - 可能是通过配置。重要的是以某种方式您能够可靠地再现每个子类型的数字。如果您将数据存储到磁盘等,则在运行时找到类型时增加计数器是不够的,因为下次运行时您可能无法以相同的顺序找到类型。所以;让我们假设通过某种机制你有一个唯一的正整数,它将 SuperHero 表示为 Person 的子类:

    int tag = 7; // why not
    Type subType = typeof(SuperHero);
    

    然后,告诉 protobuf-net 这个子类型:

    RuntimeTypeModel.Default.Add(typeof(Person), true).AddSubType(tag, subType);
    

    这相当于属性处理代码看到[ProtoInclude(...)]时所做的事情

    【讨论】:

    • 我使用的“某种机制”是创建ProtoContractAttribute 的自定义版本,以便我可以使用[ProtoContract(7)] 装饰派生类,其行为与使用@ 装饰基类的行为相同987654326@。不幸的是,属性是sealed
    • 感谢您的快速回复!这对我来说很好。
    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多