2013-04-29 114 views
1

我用從IList<string>繼承了我的Family類數據結構如下:無法序列財產

public class Family : IList<string> 
{ 
    public string LastName { get; set; } 

    //IList<string> members 
       .    . 
       . 

    //IList<string> members 
} 

創建我自己的RuntimeTypeModel並添加Family型吧喜歡這裏:

RuntimeTypeModel myModel = RuntimeTypeModel.Create(); 
MetaType familyMetaType = myModel.Add(typeof(Family), true); 
familyMetaType.AddField(1, "LastName"); 
familyMetaType.AddField(2, "Item").IsPacked = true; ; 
familyMetaType.CompileInPlace(); 
myModel.Compile(); 

然後我創建了一個Family對象,並對其進行序列化:

Family family = new Family(); 
family.LastName = "Sawan"; 
family.Add("Amer"); 

using (FileStream fs = new FileStream("Dump.proto", FileMode.Create)) 
    myModel.Serialize(fs, family); 

但是,當我反序列化它時,我只獲得string集合的成員,但沒有得到LastName值。

在這個例子中,我應該爲我的RuntimeTypeModel設置什麼樣的配置以使其它對象序列化,如LastName

回答

2

XmlSerializer一樣,protobuf-net在列表和實體之間繪製一條硬線。就protobuf-net而言,某些事情不可能同時存在。如果你不希望它選擇「列表」,你可以在[ProtoContract]上使用IgnoreListHandling(IIRC) - 但這顯然不會將列表中的項目序列化爲列表中的項目。它通常是更好地爲對象名稱和列表:

[ProtoContract] 
public class Family 
{ 
    [ProtoMember(1)] public string LastName { get; set; } 
    [ProtoMember(2)] public IList<string> Items {get{return items;}} 

    private readonly IList<string> items = new List<string>(); 
}