我正在尝试将对象序列化为XML,并且在序列化为XML时使用了一个小测试人员来试验不同的对象行为。我知道二进制序列化程序很深,XML很浅。但是,在使用XML时,它似乎尝试序列化在另一个对象中组成的List。
我的问题是我在序列化List时会复制数据。代码和输出如下:
class Program
{
static void Main(string[] args)
{
TestSerializer original = new TestSerializer();
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(original.GetType());
x.Serialize(Console.Out, original);
Console.WriteLine("\n\n\n");
using (MemoryStream stream = new MemoryStream())
{
x.Serialize(stream, original);
stream.Seek(0, SeekOrigin.Begin);
TestSerializer copy = x.Deserialize(stream) as TestSerializer;
x.Serialize(Console.Out, copy);
}
Console.ReadLine();
}
}
public class TestSerializer
{
public List<string> words = new List<string>();
public TestSerializer()
{
words.Add("word");
words.Add("anotherword");
}
}
和相应的输出:
<?xml version="1.0" encoding="IBM437"?>
<TestSerializer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=
"http://www.w3.org/2001/XMLSchema">
<words>
<string>word</string>
<string>anotherword</string>
</words>
</TestSerializer>
<?xml version="1.0" encoding="IBM437"?>
<TestSerializer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd=
"http://www.w3.org/2001/XMLSchema">
<words>
<string>word</string>
<string>anotherword</string>
<string>word</string>
<string>anotherword</string>
</words>
</TestSerializer>
正如您所看到的,当序列化“原始”时,列表内容会加倍,然后反序列化为“复制”。到目前为止,我有什么遗漏吗?似乎不应该有重复的数据。
答案 0 :(得分:3)
在TestSerializer类的构造函数上放置一个断点。你会注意到它被称为例如在以下行:
TestSerializer copy = x.Deserialize(stream) as TestSerializer;
所以当你反序列化对象时