inheritance对象的XML反序列化
我有一个对象InputFile
,它有数组和对象来保存文件的内容。 我还有从ABCFile
inheritance的ABCFile
和XYZFile
,它们将读取不同类型的文件并将它们存储到InputFile
的预计成员中。
由于这两个对象的序列化和反序列化与父对象相同,因此我在父对象上实现了标准的XML序列化接口。 在反序列化期间, Read
一些参数,调用Read
函数(加载文件),然后反序列化完成。
序列化工作很好,但反序列化( List
)不起作用,因为反序列化器调用父存根Read
文件函数而不是ABCFile
或XYZFile
。
如何让反序列化识别正确使用的对象类型? 我的List
可能有多种文件类型。
谢谢
我用来序列化对象的代码:
public class InputFileHolder : IXmlSerializable { ... public void WriteXml(XmlWriter w) { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlSerializer ifXml = new XmlSerializer(typeof(List)); ifXml.Serialize(w, InputFiles, ns); //More serialization }
我自定义序列化List时如何维护对象类型的任何想法?
尝试
[XmlArray] [XmlArrayItem(ElementName="ABCFile", Type=typeof(ABCFile))] [XmlArrayItem(ElementName="XYZFile", Type=typeof(XYZFile))] public List InputFileList { get; set; }
这将指示序列化程序,即使这是一个InputFile列表,也会有两个派生类型存储在此列表中。 它可能会使每个方法使用特定版本的方法。
如果失败,请告诉我。
根据您的评论进行修改
我不知道这是怎么回事。
我测试了以下几个类:
public class InputFile { public String InputfileCommonProperty { get; set; } } public class ABCFile : InputFile { public String ABCSpecificProperty { get; set; } } public class XYZFile : InputFile { public String XYZSpecificProperty { get; set; } } public class InputFileHolder { public InputFileHolder() { InputFileList = new List(); } [XmlArray] [XmlArrayItem(ElementName = "ABCFile", Type = typeof(ABCFile))] [XmlArrayItem(ElementName = "XYZFile", Type = typeof(XYZFile))] public List InputFileList { get; set; } }
我的主程序如下:
static void Main(string[] args) { InputFileHolder fileHolder = new InputFileHolder(); fileHolder.InputFileList.Add( new ABCFile() { InputfileCommonProperty = "This is a common property", ABCSpecificProperty = "This is a class specific property" }); XmlSerializer serializer = new XmlSerializer(typeof(InputFileHolder)); MemoryStream memoryStream = new MemoryStream(); serializer.Serialize(memoryStream, fileHolder); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); String serializedString = enc.GetString(memoryStream.ToArray()); }
最后,serializedString的内容是:
This is a common property This is a class specific property
你看? 序列化器知道它是ABCFile而不是通用的InputFile。