简体   繁体   中英

C# Exception when trying to serialize a dynamic derived object

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.

You can tell the XmlSerializer about the extra types required via the constructor at run time. For example:

var serializer = new XmlSerializer(animalList.GetType(), new[] { typeof(Elephant) });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM