我的基类和很少的派生类将属性添加到基类
到目前为止,我总是使用派生类的混合对象对列表进行序列化和反序列化,并且我唯一要做的就是添加[XmlInclude(typeof(child))]
和C#来处理剩下的事情。< / p>
这次我想直接序列化/反序列化派生类的对象,而不是把它放在列表中。最有趣的部分是,当我在列表中序列化对象时,生成的xml与“直接”序列化不同。此外 - 我不能将直接serlized-object反序列化为它的基类项的实例,而列表反序列化就好了(我在下面添加了一个例子)
这是示例类的代码:
[XmlInclude(typeof(child))]
public abstract class father
{ ... }
public class child : father
{
public double Sum { get; set; }
public char Currency { get; set; }
}
这是以下示例的初始化代码:
father oD = new child() { Currency = '$', Sum = 1 };
string xml_str = Tools.Serialize(oD);
XML输出是:
<child xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Sum>1</Sum><Currency>36</Currency></child>
当我将对象放入列表并序列化列表时,输出为
<ArrayOfFather xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><father xsi:type="child"><Sum>1</Sum><Currency>36</Currency></father></ArrayOfFather>
正如您所看到的XML不同:
<father xsi:type="child"><Sum>1</Sum><Currency>36</Currency></father>
问题在于,虽然以下两行有效(因为我将子类提供为反序列化目标):
child oD1 = Tools.DeSerializeGeneric<child>(xml_str);
father oD2 = Tools.DeSerializeGeneric<child>(xml_str);
我无法将第三个(以及我需要的那个)反序列化
father oD4 = Tools.DeSerializeGeneric<father>(xml_str);
抛出
System.InvalidOperationException: There is an error in XML document (1, 2). ---> System.InvalidOperationException: <child xmlns=''> was not expected.
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderfather.Read4_father()
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
at Tools.DeSerializeGeneric[T](String source) in Dev-testing:\Tools.cs:line 1549
at Program.Main(String[] args) in Dev-testing:\Program.cs:line 48
代码中使用的Tools.DeSerializeGeneric
是虚拟反序列化函数:
public static T DeSerializeGeneric<T>(string source)
{
XmlSerializer x = new XmlSerializer(typeof(T));
StringReader SsR = new StringReader(source);
return (T) x.Deserialize(SsR);
}
有没有办法强制对象序列化为其基类(如列表中所示)?