翻译:
尝试显示类型时发生错误 AnmialShelter.Animal
我有一个带有子类的Animal类,比如'horse'和'mouse'。
我把动物写成这样的XML:
private void writeToFile()
{
DataContractSerializer dcs = new DataContractSerializer(typeof(Animal));
using (FileStream f = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\file.xml",
FileMode.Create, FileAccess.Write))
{
foreach (Animal a in animalList)
{
dcs.WriteObject(f, a);
}
}
}
当我尝试读取xml并将对象添加到动物列表时,错误如图所示。
private List<Animal> readFromFile()
{
var myDeserializer = new XmlSerializer(typeof(Animal));
using (var myFileStream = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\file.xml", FileMode.Open))
{
animalList = (List<Animal>)myDeserializer.Deserialize(myFileStream);
}
return animalList;
}