Aar*_*ron 0 c# xml inheritance serialization
我有一个对象InputFile,它有数组和对象来保存文件的内容.我也有ABCFile和XYZFile,它们都继承InputFile将读取不同类型的文件,并将它们存储到的投影成员InputFile.
由于这两个对象的序列化和反序列化与父对象相同,因此我在父对象上实现了标准的XML序列化接口.在反序列化期间,会读取一些参数,Read调用一个函数(加载文件),然后反序列化完成.
序列化工作得很好,但反序列化(of List<InputFile>)不起作用,因为反序列化器调用父类存根Read文件函数而不是ABCFile或者XYZFile.
如何让反序列化识别正确使用的对象类型?我List<InputFile>的文件类型可能会混合在一起.
谢谢
我用来序列化对象的代码:
public class InputFileHolder : IXmlSerializable {
...
public void WriteXml(XmlWriter w) {
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
XmlSerializer ifXml = new XmlSerializer(typeof(List<InputFile>));
ifXml.Serialize(w, InputFiles, ns);
//More serialization
}
Run Code Online (Sandbox Code Playgroud)
我自定义序列化List时如何维护对象类型的任何想法?
尝试
[XmlArray]
[XmlArrayItem(ElementName="ABCFile", Type=typeof(ABCFile))]
[XmlArrayItem(ElementName="XYZFile", Type=typeof(XYZFile))]
public List<InputFile> InputFileList
{
get;
set;
}
Run Code Online (Sandbox Code Playgroud)
这将指示序列化程序,即使这是一个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<InputFile>();
}
[XmlArray]
[XmlArrayItem(ElementName = "ABCFile", Type = typeof(ABCFile))]
[XmlArrayItem(ElementName = "XYZFile", Type = typeof(XYZFile))]
public List<InputFile> InputFileList { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的主程序如下:
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());
}
Run Code Online (Sandbox Code Playgroud)
最后,serializedString的内容是:
<?xml version="1.0"?>
<InputFileHolder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InputFileList>
<ABCFile>
<InputfileCommonProperty>This is a common property</InputfileCommonProperty>
<ABCSpecificProperty>This is a class specific property</ABCSpecificProperty>
</ABCFile>
</InputFileList>
</InputFileHolder>
Run Code Online (Sandbox Code Playgroud)
你看?序列化程序知道它是ABCFile而不是通用的InputFile.
| 归档时间: |
|
| 查看次数: |
3586 次 |
| 最近记录: |