我有一个非常非常奇怪的问题。我想通过 xml 序列化一个对象。好的,所以我开始创建一个 XmlSerializer 并且没有错误 - 什么都没有。但是如果我反序列化......属性只是没有设置。另一个奇怪的事情是xml似乎没问题。
这是我的代码的一部分,其余的只是方法......
[XmlInclude(typeof(TestMapper))]
[XmlInclude(typeof(TestSource))]
[XmlInclude(typeof(TestTarget))]
public abstract class ElementBase : IElement
{
[XmlIgnore]
public IElement this[int index]
{
get
{
return Childs.ElementAt(index).Value;
}
}
List<ElementBase> _childSerializable;
[XmlArrayItem(typeof(ElementBase))]
public List<ElementBase> ChildSerializable
{
get
{
_childSerializable = Childs.Select(x => x.Value).ToList();
return _childSerializable;
}
set
{
_childSerializable = value;
foreach (ElementBase element in _childSerializable)
Childs.Add(element.Index, element);
}
}
protected Dictionary<object, ElementBase> _childs;
[XmlIgnore]
public Dictionary<object, ElementBase> Childs
{
get
{
return _childs ?? (_childs = new Dictionary<object ,ElementBase>());
}
set
{
_childs = value;
}
}
object _index = -1;
public object Index
{
get
{
return _index;
}
set
{
_index = value;
}
}
这就是我序列化的方式:
TestTarget target = new TestTarget();
TestSource source = new TestSource() { Value = "Hallo", Index = 1};
TestSource source1 = new TestSource() { Value = " Welt", Index = 2};
TestMapper mapper = new TestMapper();
target.ConnectChild(mapper);
mapper.ConnectChild(source);
mapper.ConnectChild(source1);
target.Execute();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
XmlSerializer serializer = new XmlSerializer(target.GetType());
serializer.Serialize(memStream, target);
memStream.Position = 0;
object obj = serializer.Deserialize(memStream);
target = obj as TestTarget;
memStream.Position = 0;
Console.ReadKey();
好的,现在这是最终结果:
<?xml version="1.0"?>
<TestTarget xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ChildSerializable>
<ElementBase xsi:type="TestMapper">
<ChildSerializable>
<ElementBase xsi:type="TestSource">
<ChildSerializable />
<Index xsi:type="xsd:int">1</Index>
<Value xsi:type="xsd:string">Hallo</Value>
</ElementBase>
<ElementBase xsi:type="TestSource">
<ChildSerializable />
<Index xsi:type="xsd:int">2</Index>
<Value xsi:type="xsd:string"> Welt</Value>
</ElementBase>
</ChildSerializable>
<Index xsi:type="xsd:int">-1</Index>
</ElementBase>
</ChildSerializable>
<Index xsi:type="xsd:int">-1</Index>
</TestTarget>
所以有没有人知道发生了什么错误。我已经工作了几个小时,但我找不到任何东西:((