问题
Assuming I have this sample class:
public class MyClass
{
public List<int> ListTest { get; set; }
public string StringTest { get; set; }
public int IntTest { get; set; }
}
And this code:
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);
}
After the Deserialize is completed the value of res
is:ListTest
-> Empty List with Count = 0 (NOT null).StringTest
-> "String" as expectedIntTest
-> 0 as expect (default value of an integer).
I'd like the serializer to act the same (default(List<T>)
which is null) with List's and not instantiate them.
How can I accomplish something like that?
BTW, I must use the XmlSerializer
.
回答1:
You can use backup-property to serialize/deserialize property as array:
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); }
}
...
}
回答2:
Mark your property as nullable:
public class MyClass
{
[XmlArray(IsNullable = true)]
public List<int> ListTest { get; set; }
public string StringTest { get; set; }
public int IntTest { get; set; }
}
来源:https://stackoverflow.com/questions/31984191/prevent-xmlserializer-from-auto-instantiating-lists-on-deserialize