使用XML </byte>中的List <byte>成员反序列化对象

时间:2014-10-21 03:13:00

标签: c# xml serialization xml-serialization

当类属性在类缩写器中具有默认定义时,遇到具有List<byte>公共属性的类实例的XML反序列化问题

说我们上课了:

public class TestClass
{
    public List<byte> ByteList;
    public TestClass()
    {
        this.ByteList = new List<byte>() { 0x01, 0x02 };
    }
}

然后我们有以下代码来测试序列化/反序列化

TestClass testClass = new TestClass();
Console.WriteLine("testClass.ByteList.Count: {0}", testClass.ByteList.Count);

System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TestClass));
using (System.IO.FileStream fs = new System.IO.FileStream(@".\testClass.xml", System.IO.FileMode.OpenOrCreate))
{
    xmlSerializer.Serialize(fs, testClass);
}
Console.WriteLine("testClass.ByteList.Count: {0}", testClass.ByteList.Count);

TestClass deserializedTestClass = null;
using (System.IO.FileStream sr = new System.IO.FileStream(@".\testClass.xml", System.IO.FileMode.Open))
{
    deserializedTestClass = (TestClass)xmlSerializer.Deserialize(sr);
}
Console.WriteLine("deserializedTestClass.ByteList.Count: {0}", deserializedTestClass.ByteList.Count);

因此我们在控制台上看到输出:

  

testClass.ByteList.Count:2

     

testClass.ByteList.Count:2

     

deserializedTestClass.ByteList.Count:4

序列化结果xml在这里:

<?xml version="1.0"?>
<TestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ByteList>
    <unsignedByte>1</unsignedByte>
    <unsignedByte>2</unsignedByte>
  </ByteList>
</TestClass>

有人可以解释这里发生了什么,以及如何解决它?

1 个答案:

答案 0 :(得分:0)

TestClass的无参数构造函数将ByteList初始化为非空列表(即值为{1,2})。然后,反序列化将XML中找到的两个元素添加到该非空列表中。所以当然列表中包含了所有4个元素。