2017-08-20 37 views
0

我有以下類別:試圖序列動態派生類對象時,C#異常

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

當我嘗試serilalize這個名單,我得到「System.InvalidOperationException:是沒有預料到的類型大象使用XmlInclude或SoapInclude屬性來指定靜態未知的類型「。 起初,我還爲貓,牛和狗對象得到了這個異常,並通過向它們的類中添加[XmlInclude(typeof())]來解決它,但我無法找到類似的動態派生類型解決方案,因爲這個屬性是在編譯時設置的。

回答

0

你可以告訴XmlSerializer有關在運行時通過構造函數需要的額外類型。例如:

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

謝謝!它工作完美。現在只有另外一個問題:在以前的程序運行中,在反序列化一個xml文件時,我遇到了一個異常情況,即大象是一個未知類型的異常類型的象。 desrialize必須獲得與serialize類型相同的列表,但我怎麼能給它以前創建的動態類型? – MaorK84