create TypeModel at runtime using Protobuf-Net, Unexpected sub-type
I have the class structure below and would like to serialize it at runtime using Protobuf-Net
. Unfortunately I get error "Unexpected sub-type: Web2Pdf". Why?
var web2PdfEntity = new Web2Pdf();
web2PdfEntity.Property1 = 1;
web2PdfEntity.Property2 = 2;
web2PdfEntity.Property3 = 3;
var model = TypeModel.Create();
model.Add(typeof (EntityBase), true).AddSubType(20000, typeof (WebEntity)).AddSubType(30000,typeof (Web2Pdf));
model.CompileInPlace();
using (var stream = new FileStream(@"C:\1.txt", FileMode.Create, FileAccess.Write, FileShar开发者_开发技巧e.None))
{
model.Serialize(stream, web2PdfEntity); //Get exception here!
}
[ProtoContract]
public abstract class EntityBase
{
[ProtoMember(1011)]
public int Property1 { get; set; }
}
[ProtoContract]
public abstract class WebEntity : EntityBase
{
[ProtoMember(1012)]
public int Property2 { get; set; }
}
[ProtoContract]
public sealed class Web2Pdf : WebEntity
{
[ProtoMember(1013)]
public int Property3 { get; set; }
}
The subtypes must be associated with the immediate parent, so: EntityBase
needs to know about WebEntity
, and WebEntity
needs to know about Web2Pdf
(rather than EntityBase
knowing about both and WebEntity
not knowing about Web2Pdf
).
For info, smaller tag numbers are more efficient, too - but up to you.
Additionally, this can all be done via [ProtoInclude(...)]
, which can be more convenient if the sub-type numbers are fixed.
精彩评论