如何在反序列化时覆盖默认集合

时间:2015-06-25 11:36:28

标签: c# xml-serialization

我有一个代表一堆设置的类:

public class Settings
{
   public Settings()
   {
       InnerSettings = new List<InnerSettings>();
       //this is the settings i want to have by default
       InnerSettings.Add(new InnerSettings());
   }
   [XmlArray]
   public List<InnerSettings> InnerSettings {get; set;}
}

现在,当我反序列化此对象时,XML中的InnerSettings将添加到默认List构造函数中创建的项目之上的Settings()。是否有一种简单的方法来告诉反序列化器,我想要覆盖集合,删除默认项目?

1 个答案:

答案 0 :(得分:1)

XML Serializer不支持任何回调,并且从XmlSerializer类派生,您可以覆盖的方法很少。让我们看一些(肮脏的)变通方法:

1)更改默认构造函数(将XmlSerializer将调用)以不包括默认项目。添加带伪参数的第二个构造函数并公开工厂方法:

public class Settings {
   private Settings() {
       // Called by XmlDeserializer
   }

   private Settings(int dummy) {
       // Called by factory method
       InnerSettings = new List<InnerSettings> { new InnderSettings(); }
   }

   public static Settings Create() {
       return new Settings(0);
   }
}

2)在反序列化对象后删除项目。为此创建自己的XmlSerializer

public class SettingsXmlSerializer : XmlSerializer {
    protected override object Deserialize(XmlSerializationReader reader) {
        var settings = (Settings)base.Deserialize(reader);
        settings.InnerSettings.RemoveAt(0);

        return settings;
    }
}

3)这应该是正确的方法,但对于复杂类型来说并不容易:IXmlSerializable实施的长期工作......