防止XmlSerializer在反序列化时自动实例化List的 [英] Prevent XmlSerializer from auto instantiating List's on Deserialize
本文介绍了防止XmlSerializer在反序列化时自动实例化List的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下示例类:
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
-> Count = 0(不为空)的空列表。
StringTest
->预期的字符串
IntTest
->预期为0(整数的默认值)。
After the Deserialize is completed the value of res
is:
ListTest
-> Empty List with Count = 0 (NOT null).
StringTest
-> "String" as expected
IntTest
-> 0 as expect (default value of an integer).
我希望序列化器执行相同的操作(使用List的默认值(List
(为空)并且不实例化它们。
I'd like the serializer to act the same (default(List<T>)
which is null) with List's and not instantiate them.
如何
BTW,我必须使用 XmlSerializer
。
推荐答案
您可以使用backup-property将属性序列化/反序列化为数组:
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); }
}
...
}
这篇关于防止XmlSerializer在反序列化时自动实例化List的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文