c# – 使用XmlSerializer反序列表导致额外项目

前端之家收集整理的这篇文章主要介绍了c# – 使用XmlSerializer反序列表导致额外项目前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我注意到XmlSerializer和通用列表(特别是List< int>)的奇怪行为.我想知道有没有人看过这个,或者知道发生了什么.看起来好像序列化工作正常,但是反序列化想要添加额外的项目到列表中.下面的代码演示了这个问题.

可序列化类:

  1. public class ListTest
  2. {
  3. public int[] Array { get; set; }
  4. public List<int> List { get; set; }
  5.  
  6. public ListTest()
  7. {
  8. Array = new[] {1,2,3,4};
  9. List = new List<int>(Array);
  10. }
  11. }

测试代码

  1. ListTest listTest = new ListTest();
  2. Debug.WriteLine("Initial Array: {0}",(object)String.Join(",",listTest.Array));
  3. Debug.WriteLine("Initial List: {0}",listTest.List));
  4.  
  5. XmlSerializer serializer = new XmlSerializer(typeof(ListTest));
  6. StringBuilder xml = new StringBuilder();
  7. using(TextWriter writer = new StringWriter(xml))
  8. {
  9. serializer.Serialize(writer,listTest);
  10. }
  11.  
  12. Debug.WriteLine("XML: {0}",(object)xml.ToString());
  13.  
  14. using(TextReader reader = new StringReader(xml.ToString()))
  15. {
  16. listTest = (ListTest) serializer.Deserialize(reader);
  17. }
  18.  
  19. Debug.WriteLine("Deserialized Array: {0}",listTest.Array));
  20. Debug.WriteLine("Deserialized List: {0}",listTest.List));

调试输出

  1. Initial Array: 1,4
  2. Initial List: 1,4

XML:

  1. <?xml version="1.0" encoding="utf-16"?>
  2. <ListTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  3. <Array>
  4. <int>1</int>
  5. <int>2</int>
  6. <int>3</int>
  7. <int>4</int>
  8. </Array>
  9. <List>
  10. <int>1</int>
  11. <int>2</int>
  12. <int>3</int>
  13. <int>4</int>
  14. </List>
  15. </ListTest>
  1. Deserialized Array: 1,4
  2. Deserialized List: 1,4,1,4

请注意,数组和列表似乎已经序列化为XML正确,但反序列化数组出来正确,但列表返回与一组重复的项目.有任何想法吗?

解决方法

这是因为您正在构造函数中初始化列表.当你去反序列化时,创建一个新的ListTest,然后从状态填充对象.

想像这样的工作流程

>创建一个新的ListTest
>执行构造函数(添加1,4)
>反序列化xml状态,并将1,4添加到列表

一个简单的解决方案是将该对象初始化在构造函数的范围之外.

  1. public class ListTest
  2. {
  3. public int[] Array { get; set; }
  4. public List<int> List { get; set; }
  5.  
  6. public ListTest()
  7. {
  8.  
  9. }
  10.  
  11. public void Init()
  12. {
  13. Array = new[] { 1,4 };
  14. List = new List<int>(Array);
  15. }
  16. }
  17.  
  18. ListTest listTest = new ListTest();
  19. listTest.Init(); //manually call this to do the initial seed

猜你在找的C#相关文章