C# 向后兼容的XML反序列化
我通过执行以下操作反序列化XML配置文件:C# 向后兼容的XML反序列化,c#,xml,serialization,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.De
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.Location
和config.Provider
将为空。我如何简化它,从而将config.Location
设置为typed属性的默认值(在这种情况下,字符串将设置为零长度字符串),从而允许我删除所有空检查?例如:
if (config.Description != this.Description.Text
|| config.Location != this.Location.Text
|| config.Provider != this.Provider.Text)
我知道一种选择是在反序列化的实例之外创建一个实例,并使用反射(或其他类似的方法)循环所有属性,但我希望有一种内置方法可以为未反序列化的属性指定默认值。我主要想知道这是否是正确的方法,因为在处理大量设置时,我试图减少不必要的膨胀
我已经搜索了此问题的重复项,但大多数人都试图将实例反序列化到自身中,并使用序列化事件来控制该行为。“。我希望有一种内置方法可以将默认值分配给未反序列化的属性…”
您可以在类构造函数中设置默认值。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; }
}
}
我懂了。我最近一直在使用VBA类型太多了。我在
公共字符串描述{get;set;}
中预期为“”。。。我忘记检查构造器了,谢谢。