我注意到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}", (object)String.Join(", ", 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}", (object)String.Join(", ", listTest.Array));
Debug.WriteLine("Deserialized List: {0}", (object)String.Join(", ", listTest.List));
调试输出:
Initial Array: 1, 2, 3, 4
Initial List: 1, 2, 3, 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, 2, 3, 4
Deserialized List: 1, 2, 3, 4, 1, 2, 3, 4
请注意,数组和列表似乎都已经正确序列化为XML,但在反序列化时,数组得到了正确的结果,但列表却返回了一组重复的项。有什么想法吗?