我无法使用
XML序列化将动物列表保存到磁盘.
我得到Exception:Thrown:“类型AnimalLibrary.Animals.Mammals.Dog不是预期的.使用XmlInclude或SoapInclude属性来指定静态未知的类型.” (System.InvalidOperationException)
如果我使用“Dog”尝试注释代码,它将按预期工作,并生成XML.但是作为列表中唯一元素发送的同一只狗不起作用.
[XmlElement("animalList")] public List<Animal> animalList = new List<Animal>(); public bool SaveBinary(string fileName) { Mammals.Dog dog = (Mammals.Dog)animalList[0]; //IObjectSerializer<Mammals.Dog> obj = new XMLObjectSerializer<Mammals.Dog>(); IObjectSerializer<List<Animal>> obj = new XMLObjectSerializer<List<Animal>>(); bool saved = obj.SaveFile(fileName,animalList); if (saved) return true; return false; }
XML序列化器
public bool SaveFile(string fileName,T objectToSerialize) { try { //Will overwrite old file XmlSerializer mySerializer = new XmlSerializer(typeof(T)); StreamWriter myWriter = new StreamWriter(fileName); mySerializer.Serialize(myWriter,objectToSerialize); myWriter.Close(); } catch (IOException ex) { Console.WriteLine("IO Exception ",ex.Message); return false; } return true; }
[XmlRoot(ElementName="Animal")] public abstract class Animal : IAnimal { /// <summary> /// Id of animal /// </summary> private string id; public string ID ........ [XmlRoot(ElementName = "Animals")] public abstract class Mammal : Animal { public int NumberofTeeth { get; set; } ........ [XmlRoot(ElementName="Dog")] public class Dog : Mammal { /// <summary> /// Constructor - Create an instance of a Dog /// </summary> public Dog() { } ........