2011-10-10 3 views
2

아래 클래스 구조를 가지고 있으며 런타임에 Protobuf-Net을 사용하여 직렬화하려고합니다. 불행히도 "예상치 못한 하위 유형 : Web2Pdf"오류가 발생합니다. 왜? EntityBase 필요가 알고에 대한 Web2Pdf (오히려 EntityBase보다 약 Web2Pdf를 알고 둘과 WebEntity에 대해 알고) 약 WebEntityWebEntity 요구 사항을 알고 :Protobuf-Net을 사용하여 런타임에 TypeModel을 만듭니다. 예기치 않은 하위 유형

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, FileShare.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; } 
} 

답변

2

아형은 그래서, 즉시 부모와 연결되어 있어야합니다.

정보를 얻으려면 작은 태그 번호가 더 효율적입니다. 그러나 당신에게 달려 있습니다.

또한이 작업은 모두 [ProtoInclude(...)]을 통해 수행 할 수 있습니다. 서브 유형 번호가 고정되어 있으면 더 편리 할 수 ​​있습니다.

+2

더 자세히 말하면 Marc가 말한 것 ... AddSubType()은 호출 된 것과 동일한 MetaType을 반환하므로 AddSubType() 호출을 같은 유형에 연결할 수 있습니다. 모델 [typeof (WebEntity)]. AddSubType (30000, typeof (Web2Pdf)); 모든 것을 똑바로 세우기 위해 ... – damageboy

관련 문제