2010-02-24 22 views
3

我有一個從List<T>繼承,也有一些屬性,像這樣一類序列化XML陣列和類屬性:如何使用C#XML序列化

[Serializable] 
public class DropList : List<DropItem> 
{ 
    [XmlAttribute] 
    public int FinalDropCount{get; set;} 
} 

這個類是序列化到XML作爲的一部分大類:

[Serializable] 
public class Location 
{ 
    public DropList DropList{get; set;} 
    .... 
} 

問題是,序列化程序將我的列表視爲集合;生成的XML contians僅列出元素,但不包含類屬性(本例中爲FinalDropCount)。這是輸出XML的例子:

<Location xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <DropList> 
     <DropItem ProtoId="3" Count="0" Minimum="0" Maximum="0" /> 
     <DropItem ProtoId="4" Count="0" Minimum="0" Maximum="0" /> 
    </DropList> 
    .... 
</Location> 

是否有某種方式來保存列表的內容和屬性,而不訴諸實施手工IXmlSerializable

+0

爲什麼要序列化的屬性?通常你感興趣的是類中包含的數據,也就是所有變量所具有的當前值。屬性只是一種訪問這些值的方法。你能澄清嗎? – Roast

+0

這些屬性是數據的一部分。可以這樣想:DropList是DropItem與一些附加數據的列表,如FinalDropCount。所以,我需要保存並加載所有數據 - 包括列表和屬性。 – Nevermind

回答

2

你有其他的選擇,你可以考慮。

替代一個 - 移動到組成,而不是繼承:

public class DropInfo 
{ 
    [XmlArray("Drops")] 
    [XmlArrayItem("DropItem")] 
    public List<DropItem> Items { get; set; } 

    [XmlAttribute] 
    public int FinalDropCount { get; set; } 
} 

public class Location 
{ 
    public DropInfo DropInfo { get; set; } 
} 

替代2 - 將集合之外的屬性:

public class DropList : List<DropItem> 
{ 
} 

public class Location 
{ 
    public DropList DropList { get; set; } 

    [XmlAttribute] 
    public int FinalDropCount { get; set; } 
} 
+0

這就是我現在正在做的。但是從語義上講,最好有一個DropList,它是_is_一個List--如果這是可能的話。 – Nevermind