<><>Edit>/strong> 该法典应说明整个问题:
[XmlInclude(typeof(AThing1))]
public abstract class AThing
{
public abstract string Name { get; set; }
}
[XmlInclude(typeof(IThing1))]
public interface IThing
{
string Name { get; set; }
}
public class AThing1 : AThing
{
public override string Name { get; set; }
}
public class IThing1 : IThing
{
public string Name { get; set; }
}
List<AThing> aThings = new List<AThing>(new AThing[] { new AThing1() { Name = "Bob" } });
List<IThing> iThings = new List<IThing>(new IThing[] { new IThing1() { Name = "Bob" } });
public void Test()
{
using (StringWriter sw = new StringWriter())
{
XmlSerializer aSerializer = new XmlSerializer(typeof(List<AThing>));
aSerializer.Serialize(sw, aThings);
string text = sw.ToString();
}
using (StringWriter sw = new StringWriter())
{
// This line will throw "Cannot serialize interface IThing.":
XmlSerializer iSerializer = new XmlSerializer(typeof(List<IThing>));
iSerializer.Serialize(sw, iThings);
string text = sw.ToString();
}
}
由<代码>aSerializer生成的第一个<代码>text将:
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfAThing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AThing xsi:type="AThing1">
<Name>Bob</Name>
</AThing>
</ArrayOfAThing>
我看不出为什么可以制定<代码>iSerializer?
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfIThing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<IThing xsi:type="IThing1">
<Name>Bob</Name>
</IThing>
</ArrayOfIThing>
而不是放弃例外。