尝试序列化动态派生对象时出现C#异常

时间:2017-08-20 21:16:36

标签: c# xml-serialization xmlinclude

我有以下课程:

[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();
}

当我尝试对此列表进行系列化时,我得到了#34; System.InvalidOperationException:不期望大象类型。使用XmlInclude或SoapInclude属性指定静态未知的类型&#34;。 起初我也得到了猫,牛和狗对象的这个例外,并通过在他们的类中添加[XmlInclude(typeof())]来解决它,如上所示,但我找不到动态派生类型的类似解决方案因为此属性是在编译时设置的..

1 个答案:

答案 0 :(得分:0)

您可以在运行时通过构造函数告知XmlSerializer有关所需的额外类型。例如:

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