簡體   English   中英

嘗試序列化動態派生對象時出現C#異常

[英]C# Exception when trying to serialize a dynamic derived object

我有以下課程:

[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:不需要類型大象。 使用XmlInclude或SoapInclude屬性可以指定靜態未知的類型。

起初,我還為CatCowDog對象獲得了此異常,並通過將[XmlInclude(typeof(...))]到它們的類中來解決了該異常,但是對於動態派生,我找不到類似的解決方案類型,因為此屬性是在編譯時設置的。

您可以在運行時通過構造函數告訴XmlSerializer有關所需的其他類型。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM