2015-08-13 27 views
1

假設我有這樣的示例類:防止XmlSerializer的從自動實例化列表對反序列化

public class MyClass 
{ 
    public List<int> ListTest { get; set; } 
    public string StringTest { get; set; } 
    public int IntTest { get; set; } 
} 

而這種代碼:

string xmlStr = "<MyClass><StringTest>String</StringTest></MyClass>"; 
XElement xml = XElement.Parse(xmlStr); 
XmlSerializer ser = new XmlSerializer(typeof(MyClass)); 
using (XmlReader reader = xml.CreateReader()) 
{ 
    var res = ser.Deserialize(reader); 
} 

的反序列化完成的res值之後爲:
ListTest - >計數爲0的空列表(NOT NULL)。
StringTest - >「字符串」與預期的一樣
IntTest - > 0按期望值(整數的默認值)。

我希望序列化程序的行爲相同(default(List<T>)其中爲空)與List的,而不是實例化它們。

我該如何做到這一點?
BTW,I 必須使用XmlSerializer

回答

0

標記你的財產爲可爲空:

public class MyClass 
{ 
    [XmlArray(IsNullable = true)] 
    public List<int> ListTest { get; set; } 
    public string StringTest { get; set; } 
    public int IntTest { get; set; } 
} 
+0

感謝您的回答。這仍然創建一個空列表,並且在反序列化時不爲空。 –

+3

看起來像一個bug - http://stackoverflow.com/questions/2188619/is-there-a-way-to-avoid-the-xmlserializer-to-not-initialize-a-null-property-when –

+0

@ArthurRey傷心:( – Backs

5

可以使用備份屬性序列化/反序列化屬性作爲數組:

public class MyClass 
{ 
    [XmlIgnore] 
    public List<int> ListTest { get; set; } 
    [XmlElement("ListTest")] 
    public int[] _listTest 
    { 
     get { return ListTest?.ToArray(); } 
     set { ListTest = value == null ? null : new List<int>(value); } 
    } 
    ... 
} 

相關問題