これを機能させるには、サブタイプを識別するために使用するタグ(番号)を割り当てるだけです。基本的に、コアの「プロトコルバッファ」ワイヤ仕様は継承を処理しないため、protobuf-netは継承をカプセル化としてモデル化することでそれを実現します。[ProtoMember]
、およびサブタイプを使用してプロパティ/フィールドにタグを割り当てます[ProtoInclude]
(と比較してください[XmlInclude]
)。
タグは単一のタイプ内で一意である必要がありますが、タグ1を使用する両方のレベルで例に示されているように、サブタイプで再利用できることに注意してください。
そのようです:
using System.Collections.Generic;
using ProtoBuf;
[ProtoContract]
[ProtoInclude(20, typeof(SomeDerived))]
public class SomeBase
{
[ProtoMember(1)]
public string BaseProp { get; set; }
}
[ProtoContract]
public class SomeDerived : SomeBase
{
[ProtoMember(1)]
public int DerivedProp { get; set; }
}
[ProtoContract]
public class SomeEntity
{
[ProtoMember(1)]
public List<SomeBase> SomeList;
}
class Program
{
static void Main()
{
SomeEntity orig = new SomeEntity
{
SomeList = new List<SomeBase> {
new SomeBase { BaseProp = "abc"},
new SomeDerived { BaseProp = "def", DerivedProp = 123}
}
};
var clone = Serializer.DeepClone(orig);
// clone now has a list with 2 items, one each SomeBase and SomeDerived
}
}