ProtoBuf-Net: Inheriting [ProtoMember] of type object[] from a parent class

二次信任 提交于 2019-12-11 12:59:23

问题


The object[] mList holds whatever objects that the child collection wants it to. This is supposed to be a dummy wrapper class for the rest of the more specified collections of objects.

[ProtoInclude(98, typeof(Object1CollectionProto))]
[ProtoInclude(99, typeof(Object2CollectionProto))]
[ProtoInclude(100, typeof(Object3CollectionProto))] 
public class ObjectCollectionProto
{
  protected ObjectType mCollectionType;
  protected object[] mList;
  public ObjectCollectionProto(){}

  [ProtoMember(1), DefaultValue(ObjectType.Base)]
  public ObjectType CollectionType //enumeration for type
  {
     get { return mCollectionType; }
     set { mCollectionType = value;}
  }

  [ProtoMember(2)]
  public object[] List
  {
     get { return mList; }
     set { mList = value;}
  }
}

Then we have an example child class of the above dummy wrapper that is supposed to inherit the object[] of it's desired type.

 [ProtoContract]
public class Object1CollectionProto : ObjectCollectionProto
{
  public Object1CollectionProto()
  {
  }
}

How do I go about specifying the class hierarchy so that Object1CollectionProto inherits a the object[] mList as a list of Object1's that can be serialized? Object1's can be serialized in my case already. Just not the collection version of them.


回答1:


How to serialize arrays? This is a good way to solve the problem, just remake the framework to fit this way of serializing arrays.

Also with some careful thinking I made a way of serializing that array correctly. In my case I NEVER actually serialize the PARENT class, but rather I only serialize the CHILDREN.

I removed the ProtoMember attribute from the parent class array and set the array in the children, with a specific type into the CHILDREN classes.

public class BaseCollection{
  protected object[] mList;
  /*
   * this has a lot more properties/functions that declare how I prepare  
   * collections for serialization but are superfluous for the conversation, 
   * hence the reason for me wanting to know how to do this
  */
}

public class ChildCollection : BaseCollection{
  [ProtoMember(1)]
  public Child[] childCollection
  {
    get { return mList as Child[]; }
    set { mList = value; }
  }
}


来源:https://stackoverflow.com/questions/36870536/protobuf-net-inheriting-protomember-of-type-object-from-a-parent-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!