我有一个类,其对象必须根据 bool 值序列化/反序列化一个属性
[System.SerializableAttribute()]
public class Foo
{
private string myField;
private bool myFieldSerializes;
//Parameterless construction for serializing purposes
public Foo() { }
public Foo(string myField, bool myFieldSerializes)
{
this.myField = myField;
this.myFieldSerializes = myFieldSerializes;
}
public string MyField
{
get {return this.myField;}
set {this.myField = value;}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool MyFieldSerializes
{
get {return this.myFieldSerialzes;}
set {this.myFieldSerialzes = value;}
}
}
它应该是这样工作的:
如果我创建一个实例并将 myFieldSerializes 设置为“true”,则在序列化对象(使用 XMLSerialize)时,必须序列化 myField(包含在 XML 消息中)。如果设置为“false”,则应将其忽略。
反序列化(使用 XMLDeserialize)时, bool 值 myFieldSerializes 应该告诉我 myField 是否已被反序列化(换句话说,它存在于 XML 文件中)。
实现这种行为的方式是什么?
谢谢! :)
最佳答案
您的要求与XmlSerializer
的propertyNameSpecified 模式相匹配。来自docs :
If a schema includes an element that is optional ... [one] option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName".
此模式的便利之处在于,除了记录的行为之外,在反序列化过程中,如果遇到属性,XmlSerializer
会将 propertyNameSpecified 设置为 true -- 这正是你需要什么。因此你的类应该是这样的:
public class Foo
{
private string myField;
private bool myFieldSerializes;
//Parameterless construction for serializing purposes
public Foo() { }
public Foo(string myField, bool myFieldSerializes)
{
this.myField = myField;
this.myFieldSerializes = myFieldSerializes;
}
[XmlElement(IsNullable = true)] // Emit a value even when null as long as MyFieldSpecified == true
public string MyField
{
get { return this.myField; }
set { this.myField = value; }
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool MyFieldSpecified { get { return myFieldSerializes; } set { myFieldSerializes = value; } }
}
(将 [XmlElement(IsNullable = true)]
添加到您的 MyField
属性可确保当 MyFieldSpecified == true
,即使该字段本身为 null
。)
原型(prototype) fiddle .
关于c# - 有条件地序列化/反序列化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34322386/