2011-11-03 97 views
1

我有下面的代码文件:Serialize List <ICustomClass> to xml?

public interface IMod 
{ 
    string Name { get; set; } 
    string Description { get; set; } 
    bool Enabled { get; set; } 
    List<IClassFile> ClassFiles { get; set; } 
} 
public interface IClassFile 
{ 
    string Path { get; set; } 
    string FileName { get; set; } 
    bool Enabled { get; set; } 
} 
public class ClassFile : IClassFile 
{ 
    public string Path { get; set; } 
    public string FileName { get { return System.IO.Path.GetFileName(Path); } } 
    public bool Enabled { get; set; } 

    .... 
} 
public class ZippedMod : IMod 
{ 
    public string Name { get; set; } 
    public string Description { get; set; } 
    public bool Enabled { get; set; } 
    public List<IClassFile> ClassFiles { get; set; } 

    .... 
} 
public class ConfigurationBlock 
{ 
    public List<IMod> Mods { get; set; } 

    .... 
} 

在我的整个程序的过程中,我添加了一些ZippedMod S到ConfigurationBlock,但现在我想序列化。我试图做:

using (var stream = new StreamWriter("config.xml")) 
{ 
    var ser = new XmlSerializer(typeof(ConfigurationBlock)); 
    ser.Serialize(stream, configBlock); 
} 

但我得到这个错误:

There was an error reflecting type 'MinecraftModManager.ConfigurationBlock'. 
|-Inner Exception: 
     Cannot serialize member 'MinecraftModManager.ConfigurationBlock.Mods' of type 'System.Collections.Generic.List`1[[MinecraftModManager.IMod, MinecraftModManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]', see inner exception for more details. 
     |-Inner Exception: 
      Cannot serialize member MinecraftModManager.ConfigurationBlock.Mods of type MinecraftModManager.IMod because it is an interface. 

帮助?

回答

2

由于它们的抽象特性,您无法序列化接口。大量的具体类型可以实现相同的接口,因此它会产生歧义。您必须使用具体类型。

+0

但我*有*使用接口,否则整个程序将无法正常工作。 – Entity

+0

@TheAdamGaskins一个接口不过是一个具有纯虚拟方法的抽象基类。为什么'必须'它是一个抽象基类的接口? –

+0

啊,误解你的意思是“你必须使用具体类型”。但是将接口更改为抽象类将会奇迹般地修复一切......? – Entity

0

您不能序列化接口,只能使用默认的XmlSerializer对具体类进行序列化。您可能能够实施IXmlSerializable来覆盖此行为。