1

我有以下课程:

[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:类型 Elephant 不是预期的。使用 XmlInclude 或 SoapInclude 属性指定静态未知的类型。

起初,我也遇到了Cat,CowDog对象的异常,并通过添加[XmlInclude(typeof(...))]到它们的类来解决它,如上所示,但我找不到动态派生类型的类似解决方案,因为此属性是在编译时设置的。

4

1 回答 1

3

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

var serializer = new XmlSerializer(animalList.GetType(), new[] { typeof(Elephant) });
于 2017-08-20T22:33:14.377 回答