ProtoBuf-Net ProtoInclude Generic Type Subclass

前端 未结 2 1680
迷失自我
迷失自我 2020-12-19 12:07

I\'m having some problems with ProtoBuf-Net with a subclass of an object which inherits from a generic class.

My inheritance tree looks like this:

No         


        
2条回答
  •  天涯浪人
    2020-12-19 12:28

    I had the exact same problem, but rather than configuring all the types by hand, the method below seems to work for any type. Call it prior to serialization/deserialization.

    private void PopulateTypes(Type t)
    {
        foreach(object mt in RuntimeTypeModel.Default.GetTypes())
        {
            MetaType theType = mt as MetaType;
            if (null != theType)
            {
                if (theType.Type == t)
                    return;
            }
        }
    
        Type objType = typeof (object);
        List inheritanceTree = new List();
        do
        {
            inheritanceTree.Insert(0, t);
            t = t.BaseType;
        } while (null != t && t != objType);
    
        if (!inheritanceTree.Any(gt => gt.IsGenericType))
            return;
    
        int n = 100;
        for (int i = 0; i < inheritanceTree.Count - 1; i++)
        {
            Type type = inheritanceTree[i];
            MetaType mt = RuntimeTypeModel.Default.Add(type, true);
            mt.AddSubType(n++, inheritanceTree[i + 1]);
        }
    }
    

提交回复
热议问题