ProtoBuf-Net:从父类继承object []类型的[ProtoMember]

时间:2016-04-26 16:22:00

标签: inheritance protobuf-net protocol-buffers

对象[] mList包含子集合想要的任何对象。 这应该是其他更多指定对象集合的虚拟包装类。

[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;}
  }
}

然后我们有一个上面的虚拟包装器的示例子类,它应该继承它所需类型的对象[]。

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

如何指定类层次结构,以便Object1CollectionProto继承对象[] mList作为可以序列化的Object1列表? Object1可以在我的情况下序列化。只是不是它们的集合版本。

1 个答案:

答案 0 :(得分:0)

How to serialize arrays? 这是解决问题的好方法,只需重新构建框架以适应这种序列化数组的方式。

另外,经过仔细考虑,我提出了一种正确序列化数组的方法。在我的情况下,我从不实际序列化 PARENT 类,但我只序列化 CHILDREN

我从父类数组中删除了ProtoMember属性,并将子类中的数组设置为CHILDREN类中的特定类型。

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; }
  }
}