2012-02-12 50 views

回答

4

通常使用具有多個派生類型的抽象類來允許使用強類型列表等。

例如,您可能有一個DocumentFragment類,它是抽象的和兩個名爲TextDocumentFragment和CommentDocumentFragment的具體類(此示例來自Willis)。

這允許創建一個List屬性,它只能包含這兩種類型的對象。

如果試圖創建一個返回該列表中你會得到一個錯誤一個WebService,但是這是很容易用下面的代碼來解決....

[Serializable()] 
[System.Xml.Serialization.XmlInclude(typeof(TextDocumentFragment))] 
[System.Xml.Serialization.XmlInclude(typeof(CommentDocumentFragment))] 
public abstract class DocumentFragment { 
...} 

的XmlInclude屬性告訴類,它可能被序列化爲這兩個派生類。

這將在DocumentFragment元素中生成一個指定實際類型的屬性,如下所示。

<DocumentFragment xsi:type="TextDocumentFragment"> 

使用此方法還將包含特定於派生類的任何附加屬性。

11

另一種方法是使用XmlElementAttribute移動已知類型的泛型列表本身的列表...

using System; 
using System.Xml; 
using System.Xml.Serialization; 
using System.Collections.Generic; 

public abstract class Animal 
{ 
    public int Weight { get; set; }  
} 

public class Cat : Animal 
{ 
    public int FurLength { get; set; }  
} 

public class Fish : Animal 
{ 
    public int ScalesCount { get; set; }  
} 

public class AnimalFarm 
{ 
    [XmlElement(typeof(Cat))] 
    [XmlElement(typeof(Fish))] 
    public List<Animal> Animals { get; set; } 

    public AnimalFarm() 
    { 
     Animals = new List<Animal>(); 
    } 
} 

public class Program 
{ 
    public static void Main() 
    { 
     AnimalFarm animalFarm = new AnimalFarm(); 
     animalFarm.Animals.Add(new Cat() { Weight = 4000, FurLength = 3 }); 
     animalFarm.Animals.Add(new Fish() { Weight = 200, ScalesCount = 99 }); 
     XmlSerializer serializer = new XmlSerializer(typeof(AnimalFarm)); 
     serializer.Serialize(Console.Out, animalFarm); 
    } 
} 

...這也將導致一個更好看的XML輸出(不難看xsi:type屬性)...

<?xml version="1.0" encoding="ibm850"?> 
<AnimalFarm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Cat> 
    <Weight>4000</Weight> 
    <FurLength>3</FurLength> 
    </Cat> 
    <Fish> 
    <Weight>200</Weight> 
    <ScalesCount>99</ScalesCount> 
    </Fish> 
</AnimalFarm> 
+0

如果你不想保留Animals元素,你可以使用XmlArrayItemAttribute來代替。 – Console 2014-11-10 09:14:19