简体   繁体   English

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

[英]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. System.InvalidOperationException:不需要类型大象。 Use the XmlInclude or SoapInclude attribute to specify types that are not known statically. 使用XmlInclude或SoapInclude属性可以指定静态未知的类型。

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. 起初,我还为CatCowDog对象获得了此异常,并通过将[XmlInclude(typeof(...))]到它们的类中来解决了该异常,但是对于动态派生,我找不到类似的解决方案类型,因为此属性是在编译时设置的。

You can tell the XmlSerializer about the extra types required via the constructor at run time. 您可以在运行时通过构造函数告诉XmlSerializer有关所需的其他类型。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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