繁体   English   中英

具有不同子类的XML序列化

[英]XML Serialization with Different Subclasses

我有一个超类和两个子类,我想将这些子类的对象序列化为列表并反序列化

我试图使用一个超类列表,该列表具有两个子类中的对象,但最终出现异常。

有什么办法吗?

Type1 t = new Type1() { text="123" ,opt1=true,opt2=true};
Type2 t1 = new Type2() { text="1234",isAnswer=false};
Question q1 = new Question() { text="12321"};
Question q2 = new Question() { text = "12321" };
List<Question> q = new List<Question>() { t1 };
FileStream fs = new FileStream("aa.xml", FileMode.OpenOrCreate, FileAccess.Write);
XmlSerializer xs = new XmlSerializer(typeof(List<Question>));
//Exception is generated here InvalidOperationException
//there was error genearating the XML document
xs.Serialize(fs, q);

fs.Close();

尝试将序列号已知的类型传递给,例如,

serializer = new XmlSerializer(typeof(T), extraTypes); 其中extraTypes是必须序列化的类型数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM