c# - 向后兼容的 XML 反序列化

标签 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 的旧配置文件,则 config.Locationconfig.Provider 将为空XML 文件被反序列化。我怎样才能简化它,以便将 config.Location 设置为类型化属性的默认值(在这种情况下,字符串将设置为零长度字符串),让我放弃所有空检查?例如:

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

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

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

最佳答案

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; }
    }
}

关于c# - 向后兼容的 XML 反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21096834/

相关文章:

c# - 从文件名中删除特殊字符

c# - 使用HashSet避免重复有效吗?

c# - 将按钮附加到 C# Compact Framework .Net 2.0 中的列数据网格

php - xPath SimpleXMLElement 中的 XML 子节点

c# - 用于生成 XML 文件的机器学习算法

python - 使用用户定义的类作为值序列化 Python 中的字典 (Flask)

c# - 在c#中读取加密的文本文件

java - 如何从 Servlet 获取 XML 文件

java - java中序列化/反序列化单例类或没有默认或无参数构造函数的类?

c# - 反序列化使用不同版本的已签名程序集编写的泛型的最佳方法是什么?