2013-01-11 19 views
1

我要弄平用來定義一個protobuf網合同,我們目前擁有的線沿線的東西類型層次:平展protobufs網合同

[ProtoContract] 
public class SubClass : BaseClass 
{ 
    [ProtoMember(1)] 
    public string Prop1 { get; set; } 
} 

[ProtoContract] 
[ProtoInclude(1, typeof(SubClass))] 
public class BaseClass 
{ 
    [ProtoMember(100)] 
    public string Prop2 { get; set; } 
} 

然後重構這

[ProtoContract] 
public class SubClass 
{ 
    [ProtoMember(1)] 
    public string Prop1 { get; set; } 

    [ProtoMember(100)] 
    public string Prop2 { get; set; } 
} 

這樣,重構之前序列化的實例被成功反序列化。這可能只是通過選擇正確的索引或我需要做更多的事情嗎?

+1

作爲一個側面說明;儘可能使用較小的字段數值是值得的;特別是1-31便宜; 100稍微昂貴一點(每場1個額外的字節) –

回答

1

在引擎蓋下,protobuf-net中的繼承以基本上是多級操作的方式實現。對它進行建模不是微不足道的,坦率地說,使用像自動映射器這樣的東西可能會更容易,即將數據加載到舊的模型中;將其映射到新型號型號;序列化新模型。請注意,這是一次重大更改,之後數據將不兼容。你可以,但是,這樣做在一個模型如果你可以用醜陋的一點點生活(雖然鈔票。我只好給不同的場數,使其工作):

[ProtoContract] 
public class NewClass 
{ 
    [ProtoMember(2)] 
    public string Prop1 { get; set; 

    [ProtoMember(100)] 
    public string Prop2 { get; set; } 

    [ProtoMember(1)] // this 1 is from ProtoMember 
    private Shim ShimForSerialization { get { return new Shim(this); } } 

    // this disables the shim during serialiation; only Prop1 and Prop2 will 
    // be written 
    public bool ShouldSerializeShimForSerialization() { return false; } 

    [ProtoContract] 
    private class Shim { 
     private readonly NewClass parent; 
     public Shim(NewClass parent) { 
      this.parent = parent; 
     } 
     [ProtoMember(1)] 
     public string Prop1 { 
      get { return parent.Prop1;} 
      set { parent.Prop1 = value;} 
     } 

    } 
}