简体   繁体   English

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

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

Have come across XML deserialization issue of class instances with List<byte> public properties when that properties have default definition in class constrictor 当属性在类压缩器中具有默认定义时,遇到带有List<byte>公共属性的类实例的XML反序列化问题

Say we have class: 说我们上课:

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

then we have following code to test serialization/deserialization 然后我们有以下代码来测试序列化/反序列化

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);

as a result we see on console following output: 结果,我们在控制台上看到以下输出:

testClass.ByteList.Count: 2 testClass.ByteList.Count:2

testClass.ByteList.Count: 2 testClass.ByteList.Count:2

deserializedTestClass.ByteList.Count: 4 deserializedTestClass.ByteList.Count:4

serialization result xml is here: 序列化结果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>

Could somebody explain what is going on here and how to fix it? 有人可以解释这里发生了什么以及如何解决它吗?

The parameterless constructor for TestClass initializes ByteList to a non-empty list (ie with the values { 1, 2 }). TestClass的无参数构造函数将ByteList初始化为非空列表(即,值为{1,2})。 Then the deserialization adds the two elements found in the XML to that non-empty list. 然后反序列化将XML中找到的两个元素添加到该非空列表中。 So of course the list winds up with all 4 elements. 因此,该列表当然包含所有4个元素。

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

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