假设我们有一个可以被XmlSerializer序列化/反序列化的类.会是这样的:
- [XmlRoot("ObjectSummary")]
- public class Summary
- {
- public string Name {get;set;}
- public string IsValid {get;set;}
- }
我们有一个xml将是这样的:
- <ObjectSummary>
- <Name>some name</Name>
- <IsValid>Y</IsValid>
- <ObjectSummary>
使用布尔属性IsValid而不是string属性是更好的决定,但在这种情况下,我们需要添加一些额外的逻辑来将数据从字符串转换为bool.
解决这个问题的简单而直接的方法是使用额外的属性并将一些转换逻辑放入IsValid getter中.
任何人都可以提出更好的决定吗?使用类型转换器的属性不知何故或类似的东西?
解决方法
将节点视为自定义类型:
- [XmlRoot("ObjectSummary")]
- public class Summary
- {
- public string Name {get;set;}
- public BoolYN IsValid {get;set;}
- }
然后在自定义类型上实现IXmlSerializable:
- public class BoolYN : IXmlSerializable
- {
- public bool Value { get; set }
- #region IXmlSerializable members
- public System.Xml.Schema.XmlSchema GetSchema() {
- return null;
- }
- public void ReadXml(System.Xml.XmlReader reader) {
- string str = reader.ReadString();
- reader.ReadEndElement();
- switch (str) {
- case "Y":
- this.Value = true;
- break;
- case "N":
- this.Value = false;
- break;
- }
- }
- public void WriteXml(System.Xml.XmlWriter writer) {
- string str = this.Value ? "Y" : "N";
- writer.WriteString(str);
- writer.WriteEndElement();
- }
- #endregion
- }
您甚至可以将该自定义类改为struct,并在它和bool之间提供隐式转换,使其更加“透明”.