【问题标题】:C# Exception when trying to serialize a dynamic derived object尝试序列化动态派生对象时出现 C# 异常
【发布时间】:2019-06-06 23:50:36
【问题描述】:

我有以下课程:

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

还有如下代码sn-p:

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 属性指定类型 静态未知。

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

【问题讨论】:

    标签: c# xml-serialization xmlinclude


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!它工作得很好。只是现在另一个问题:我在反序列化 xml 文件时遇到了一个异常,即大象是未知类型,在以前的程序运行中保存了大象的类型。反序列化必须获得与序列化相同的类型列表,但是我怎样才能给它之前创建的动态类型呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多