我有以下代码文件:
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
添加了一些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.
帮助?
答案 0 :(得分:2)
由于接口的抽象性,您无法序列化接口。许多具体类型可以实现相同的接口,因此会产生歧义。您必须使用具体类型。
答案 1 :(得分:0)
您不能序列化接口,只能使用默认XmlSerializer的具体类。您可以实现IXmlSerializable来覆盖此行为。