我有以下类:
[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() {}
}
以及以下代码片段:
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:未预料到大象类型。 使用 XmlInclude 或 SoapInclude 属性指定以下类型 静态未知。
起初我也得到了Cat
、Cow
和Dog
对象的异常,并通过向它们的类添加[XmlInclude(typeof(...))]
来解决它,如上所示,但我找不到动态派生类型的类似解决方案,因为此属性是在编译时设置的。
您可以在运行时通过构造函数告诉XmlSerializer
所需的额外类型。例如:
var serializer = new XmlSerializer(animalList.GetType(), new[] { typeof(Elephant) });