2012-06-26 89 views
0

我有一個類繼承了一個集合,特別是列表<>,並且列出了下面的類。我使用DataContractSerializer將對象序列化到XML時遇到的問題是我在對象中添加的其他字段沒有被序列化器序列化。
這裏是類:使用CollectionDataContactAttribute序列化其他字段


[CollectionDataContract(Name = "ServiceEvents", Namespace = "")] 
public class ServiceEventList : List<ServiceEvent> 
{ 
    [DataMember] 
    public long StaleDate { get; set; } 

    [DataMember] 
    public long ExpirationDate { get; set; } 
} 

當我序列化對象,並寫入到磁盤,這裏是輸出(注意兩者StaleDate和到期日期失蹤)。


<ServiceEvents xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ServiceEvent><Date>2012-06-26T22:23:24.120817Z</Date><Description>A Service Event</Description><Id>634763462041210040</Id><Notes></Notes><Odometer>42</Odometer></ServiceEvent></ServiceEvents> 

下面是序列化對象的代碼:

using (FileStream fs = new FileStream(path, FileMode.Create)) 
{ 
    //TODO: StaleDate is not serializing to disk 
    //TODO: ExpirationDate is not serializing to disk 
    DataContractSerializer ser = new DataContractSerializer(typeof(ServiceEventList)); 
    ser.WriteObject(fs, list); 
} 

我的下一個想法是去除繼承結構,只是嵌入列表對象進級。如果社區確認我的方法無效,我寧願只擴展List,但不會浪費更多時間。預先感謝您的建議。

回答

2

根據這個帖子:

http://social.msdn.microsoft.com/Forums/eu/wcf/thread/57eb195a-43a9-47fe-8b1a-a9d23feb2df2

問題確實是你從一個集合類型繼承 - 在這種情況下,DataContractSerializer的序列化只是它的項目,但沒有任何額外的屬性。

+0

同意;感謝您鏈接到另一個線程。他們對「_WCF如何將收藏當作T [] _」的線材的解釋有助於平息我的好奇心。我會將我的實現恢復爲只包含List 集合作爲類內的屬性,而不是繼承列表。 – benhorgen