C# 从XML反序列化具有列表成员的对象
当列表公共属性在类constrator中具有默认定义时,遇到了具有该属性的类实例的XML反序列化问题 假设我们有课:C# 从XML反序列化具有列表成员的对象,c#,xml,serialization,xml-serialization,C#,Xml,Serialization,Xml Serialization,当列表公共属性在类constrator中具有默认定义时,遇到了具有该属性的类实例的XML反序列化问题 假设我们有课: public class TestClass { public List<byte> ByteList; public TestClass() { this.ByteList = new List<byte>() { 0x01, 0x02 }; } } 因此,我们在控制台上看到以下输出: testClass
public class TestClass
{
public List<byte> ByteList;
public TestClass()
{
this.ByteList = new List<byte>() { 0x01, 0x02 };
}
}
因此,我们在控制台上看到以下输出:
testClass.ByteList.Count:2
testClass.ByteList.Count:2
反序列化TestClass.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个元素。因此,如果我理解正确,当反序列化到泛型列表时,XmlSerializer的预期行为不是分配新的反序列化值,而是在集合上执行AddRange?我认为文档在这一点上是模糊的。但实际上发生了什么很清楚,所以从这个意义上说,是的。如果已初始化字段的对象,序列化程序将重用该对象,而不是为您创建新对象。
<?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>