繁体   English   中英

用列表反序列化对象 <byte> XML的成员

[英]Deserialize object with List<byte> member from XML

当属性在类压缩器中具有默认定义时,遇到带有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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM