I have the following classes:
[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() {}
}
And the following code snippet:
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();
}
When I try to serialize this list I get the error:
System.InvalidOperationException: The type Elephant was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.
At first I also got this exception for Cat
, Cow
and Dog
objects and solved it by adding [XmlInclude(typeof(...))]
to their classes as seen above, but I can't find a similar solution for a dynamic derived type since this attribute is set at compile time.