向后兼容的XML反序列化

时间:2014-01-13 16:51:44

标签: c# xml serialization

我通过执行以下操作来反序列化XML配置文件:

XmlSerializer deserializer = new XmlSerializer(typeof(MyType));
using (TextReader textReader = new StreamReader(fn))
{
    return (MyType)deserializer.Deserialize(textReader);
}

然后我有一个简单的方法来检查XML配置文件是否与当前UI中的值匹配。

if ((config.Description == null || config.Description != this.Description.Text)
   || (config.Location == null || config.Location != this.Location.Text)
   || (config.Provider == null || config.Provider != this.Provider.Text))

因此,如果我有一个仅包含config.Description的旧配置文件,则在反序列化XML文件时,config.Locationconfig.Provider将为null。我怎样才能简化这一点,以便将config.Location设置为typed属性的默认值(在这种情况下,字符串将设置为零长度字符串),允许我删除所有空检查?例如:

if (config.Description != this.Description.Text
   || config.Location != this.Location.Text
   || config.Provider != this.Provider.Text)

我知道一个选项是在反序列化实例之外创建一个实例,并使用Reflection(或其他类似的方法)循环遍历所有属性,但我希望有一种内置方法可以为默认值分配默认值反序列化。我主要想知道这是否是正确的方法,因为我在处理大量设置时试图减少不必要的膨胀。

我已经搜索了这个问题的重复项,但大多数人都试图将一个实例反序列化为自身并使用序列化事件来控制该行为。

2 个答案:

答案 0 :(得分:0)

“..我希望有一种内置的方法可以为未反序列化的属性分配默认值。” 您可以在类构造函数中设置默认值。

答案 1 :(得分:0)

XmlSerializer需要无参数构造函数。但是,您可以使用如下所示的任何初始化技术:

public class MyType
{
    private string _description = default(string); // Note the default is NULL, not "" for a string

    // However, why not determine the default yourself?
    private string _location = "";
    private string _provider;

    public MyType()
    {
        // Or use the constructor to set the defaults
        _provider = string.Empty;
    }

    public string Description
    {
        get { return _description; }
        set { _description = value; }
    }
}