我注意到XmlSerializer和通用列表(特别是List< int>)的奇怪行为.我想知道有没有人看过这个,或者知道发生了什么.看起来好像序列化工作正常,但是反序列化想要添加额外的项目到列表中.下面的代码演示了这个问题.
可序列化类:
public class ListTest
{
public int[] Array { get; set; }
public List<int> List { get; set; }
public Listtest()
{
Array = new[] {1,2,3,4};
List = new List<int>(Array);
}
}
测试代码:
ListTest listTest = new Listtest();
Debug.WriteLine("Initial Array: {0}",(object)String.Join(",",listTest.Array));
Debug.WriteLine("Initial List: {0}",listTest.List));
XmlSerializer serializer = new XmlSerializer(typeof(ListTest));
StringBuilder xml = new StringBuilder();
using(TextWriter writer = new StringWriter(xml))
{
serializer.Serialize(writer,listTest);
}
Debug.WriteLine("XML: {0}",(object)xml.ToString());
using(TextReader reader = new StringReader(xml.ToString()))
{
listTest = (ListTest) serializer.Deserialize(reader);
}
Debug.WriteLine("Deserialized Array: {0}",listTest.Array));
Debug.WriteLine("Deserialized List: {0}",listTest.List));
调试输出:
Initial Array: 1,4 Initial List: 1,4
XML:
<?xml version="1.0" encoding="utf-16"?>
<ListTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Array>
<int>1</int>
<int>2</int>
<int>3</int>
<int>4</int>
</Array>
<List>
<int>1</int>
<int>2</int>
<int>3</int>
<int>4</int>
</List>
</ListTest>
Deserialized Array: 1,4 Deserialized List: 1,4,1,4
请注意,数组和列表似乎已经序列化为XML正确,但反序列化数组出来正确,但列表返回与一组重复的项目.有任何想法吗?
解决方法
这是因为您正在构造函数中初始化列表.当你去反序列化时,创建一个新的ListTest,然后从状态填充对象.
想像这样的工作流程
>创建一个新的ListTest
>执行构造函数(添加1,4)
>反序列化xml状态,并将1,4添加到列表
一个简单的解决方案是将该对象初始化在构造函数的范围之外.
public class ListTest
{
public int[] Array { get; set; }
public List<int> List { get; set; }
public Listtest()
{
}
public void Init()
{
Array = new[] { 1,4 };
List = new List<int>(Array);
}
}
ListTest listTest = new Listtest();
listTest.Init(); //manually call this to do the initial seed