序列化List< ICustomClass>为xml

本文关键字:xml ICustomClass List 序列化 | 更新日期: 2023-09-27 18:13:16

我有以下代码文件:

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; }
    ....
}

在整个程序过程中,我向ConfigurationBlock添加了一些ZippedMod s,但现在我想对它们进行序列化。我试着做:

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.

帮助吗?

序列化List< ICustomClass>为xml

由于接口的抽象性质,您不能序列化接口。许多具体类型可以实现相同的接口,因此会产生歧义。必须使用具体类型

您不能序列化接口,只能使用默认XmlSerializer序列化一个具体的类。您可以实现IXmlSerializable来覆盖此行为。