我有一个超类和两个子类,我希望将子类的对象序列化为列表并反序列化
我尝试使用一个超类列表,该列表包含来自两个子类的对象,但结果却是异常。
有什么办法吗?
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();
答案 0 :(得分:4)
尝试传递序列化程序已知的类型,例如
serializer = new XmlSerializer(typeof(T), extraTypes);
其中extraTypes是必须序列化的类型数组。