我有基类和少数派生类向基类添加属性
直到现在,我总是序列化和反序列化的列表充满了派生类的混合对象,而我唯一要做的就是添加[XmlInclude(typeof(child))]
和 C# 来处理其余的事情。
这次我想直接序列化/反序列化派生类的对象,而不是将其放入列表中。最有趣的部分是,当我在列表中序列化对象时,生成的 xml 与“直接”序列化不同。此外 - 我无法将直接序列化对象反序列化为其基类项的实例,而列表反序列化就好了(我在下面添加了一个示例)
这是示例类的代码:
[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);
}
有没有办法强制对象序列化为其基类(就像它在列表中发生的那样)?