C# 反序列化派生类型

C# 反序列化派生类型,c#,xml-serialization,C#,Xml Serialization,我以为我终于理解了XmlSerialization,但我最后的方法让我觉得自己完全是个新手。 我的意图是创建一个对某种配置进行序列化和反序列化的框架。因此,我创建了一个配置类,如下所示: /// <summary> /// Application-wide configurations that determine how to transform the features. /// </summary> [XmlRoot(Namespace = "baseNS")]

我以为我终于理解了XmlSerialization,但我最后的方法让我觉得自己完全是个新手。 我的意图是创建一个对某种配置进行序列化和反序列化的框架。因此,我创建了一个配置类,如下所示:

/// <summary>
/// Application-wide configurations that determine how to transform the features. 
/// </summary>
[XmlRoot(Namespace = "baseNS")]
public class Config
{
    /// <summary>
    /// List of all configuration-settings of this application
    /// </summary>
    [System.Xml.Serialization.XmlElement("Setting")]
    public List<Setting> Settings = new List<Setting>();
}
现在,当执行上述操作时,我得到错误
“类型BW\u设置不是预期的。请使用xmlclude…”

我可以更改自定义程序集中的所有内容,但因此基础程序集属于框架,我无法更改它。你能帮我完成序列化(和反序列化)工作吗?

我通过定义一些覆盖最终实现了它:

// determine that the class BW_Setting overrides the elements within "Settings"
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(
    typeof(Config), 
    "Settings", new XmlAttributes { 
        XmlElements = { 
            new XmlElementAttribute("Setting", typeof(BW_Setting)) } });
XmlSerializer ser = new XmlSerializer(typeof(Config), overrides);
这将产生以下输出

<?xml version="1.0"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="baseNS">
  <Setting id="0">
    <CQLQuery>test</CQLQuery>
  </Setting>
</Config>

测试
唯一令人不快的是,XML中用于标记设置的名称空间丢失了。然而,反序列化也可以工作,所以这并不是那么烦人

// determine that the class BW_Setting overrides the elements within "Settings"
XmlAttributeOverrides overrides = new XmlAttributeOverrides();
overrides.Add(
    typeof(Config), 
    "Settings", new XmlAttributes { 
        XmlElements = { 
            new XmlElementAttribute("Setting", typeof(BW_Setting)) } });
XmlSerializer ser = new XmlSerializer(typeof(Config), overrides);
<?xml version="1.0"?>
<Config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="baseNS">
  <Setting id="0">
    <CQLQuery>test</CQLQuery>
  </Setting>
</Config>