【发布时间】:2019-06-06 23:50:36
【问题描述】:
我有以下课程:
[XmlInclude(typeof(Cat))]
[XmlInclude(typeof(Dog))]
[XmlInclude(typeof(Cow))]
[Serializable]
public abstract class Animal
{
public string Name { get; set; }
}
public class Cow : Animal
{
public Cow(string name) { Name = name; }
public Cow() { }
}
public class Dog : Animal
{
public Dog(string name) { Name = name; }
public Dog() { }
}
public class Cat : Animal
{
public Cat(string name) { Name = name; }
public Cat() {}
}
还有如下代码sn-p:
var animalList = new List<Animal>();
Type type = AnimalTypeBuilder.CompileResultType("Elephant", propertiesList);
var elephant = Activator.CreateInstance(type);
animalList.Add(new Dog());
animalList.Add(new Cat());
animalList.Add(new Cow());
animalList.Add((Animal)elephant);
using (var writer = new System.IO.StreamWriter(fileName))
{
var serializer = new XmlSerializer(animalList.GetType());
serializer.Serialize(writer, animalList);
writer.Flush();
}
当我尝试序列化此列表时出现错误:
System.InvalidOperationException:类型 Elephant 不是预期的。 使用 XmlInclude 或 SoapInclude 属性指定类型 静态未知。
起初我也遇到了 Cat、Cow 和 Dog 对象的异常,并通过将 [XmlInclude(typeof(...))] 添加到它们的类中来解决它,如上所示,但我找不到类似的动态解决方案派生类型,因为此属性是在编译时设置的。
【问题讨论】:
标签: c# xml-serialization xmlinclude