我正在序列化一个类,它有一个 boolean
参数。如果此参数的值为 false
,我想隐藏它。下面是类-
public class UserPreferences
{
[XmlAttributeAttribute("Name")]
public string Name;
[XmlAttributeAttribute("SaveOnClose")]
public bool SaveOnClose;
public UserPreferences() { }
public UserPreferences(string Name)
{
this.Name = Name;
}
public UserPreferences(string Name, bool SaveOnClose)
{
this.Name = Name;
this.SaveOnClose = SaveOnClose;
}
}
下面是主要方法-
UserPreferences userPreferences = new UserPreferences("guest");
XmlSerializer serializer = new XmlSerializer(typeof(UserPreferences));
serializer.Serialize(Console.Out, userPreferences);
下面是这段代码的输出-
<?xml version="1.0" encoding="IBM437"?>
<UserPreferences xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="guest" SaveOnClose="false" />
请注意参数 SaveOnClose
为 false。在这种情况下是否可以隐藏此参数?由于 false
在这里被视为默认值。
此外,如果隐藏此参数并且我反序列化上述 XML,则参数 SaveOnClose
应假定为 false
。
最佳答案
是的,这是可能的。
添加一个方法 ShouldSerializeSaveOnClose() 并让它在属性 SaveOnClose 不应被序列化时返回 false。
public bool ShouldSerializeSaveOnClose() {
return SaveOnClose == true;
}
或者,除了添加方法之外,您还可以添加指定的属性。 此外,在该属性上添加一个 XmlIgnore 属性以防止它被序列化。
[XmlIgnore]
public bool SaveOnCloseSpecified
{
get { return SaveOnClose == true; }
}
关于c# - 如果在 C# 中的 XmlSerialization 中为 false,则隐藏 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26124018/