Protobuf attributes with a hierarchy of generic classes

后端 未结 2 368
臣服心动
臣服心动 2020-12-21 15:40

I have a class hierarchy that looks like this. These classes contain a lot of other details which I have excluded. This is a simplification to focus on the serialization a

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 16:22

    I'm not 100% sure I understand the scenario you want to model; however, [ProtoInclude] only looks one level of inheritance away.

    If I understand correctly, try the following; note that you would need to know the potential generic types at compile time at the moment:

    using System;
    using ProtoBuf;
    [ProtoContract]
    [ProtoInclude(2, typeof(Response))]
    [ProtoInclude(3, typeof(Query))]
    class Packet
    {
        [ProtoMember(1)]
        int ID;
    }
    [ProtoContract]
    [ProtoInclude(1, typeof(Response))]
    [ProtoInclude(2, typeof(Response))]
    [ProtoInclude(3, typeof(Response))]
    class Response : Packet
    {
    }
    [ProtoContract]
    class Response : Response
    {
        [ProtoMember(2)]
        public T Value;
    
        public override string ToString()
        {
            return typeof(T).Name + ": " + Value;
        }
    }
    static class Program
    {
        static void Main()
        {
            Packet packet = new Response { Value = 123 };
            Packet clone = Serializer.DeepClone(packet);
            Console.WriteLine(clone.ToString()); // should be int/123
        }
    }
    

提交回复
热议问题