我通过执行以下操作反序列化 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.Location
和 config.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/