我有一个类,其中有许多公共字段,这些字段标有XML可序列化属性:
[XmlAttribute]
public string ExampleField = string.Empty;
我打算将这些字段(以及仅这些字段)重构为自动属性:
[XmlAttribute]
public string ExampleField { get; set; }
使用以前版本的类创建的实例反序列化是否会出现任何问题?
答案 0 :(得分:3)
看起来效果很好......
(XmlSerializer
是我的 .Net Xml序列化类的包装。)
[Test]
public void XmlOutTest()
{
var field = new Field { ExampleField = "TEXT" };
var property = new Property() { ExampleField = "TEXT" };
var fieldXml = XmlSerializer<Field>.Serialize(field);
var propertyXml = XmlSerializer<Property>.Serialize(property);
System.Console.WriteLine(fieldXml);
System.Console.WriteLine(propertyXml);
Assert.IsNotNull(XmlSerializer<Field>.Deserialize(propertyXml));
Assert.IsNotNull(XmlSerializer<Property>.Deserialize(fieldXml));
}
public class Field
{
public string ExampleField = string.Empty;
}
// changing root so I can use each other's xml when deserializing
[System.Xml.Serialization.XmlRoot("Field")]
public class Property
{
public string ExampleField { get; set; }
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<Field>
<ExampleField>TEXT</ExampleField>
</Field>
<?xml version="1.0" encoding="utf-16"?>
<Field>
<ExampleField>TEXT</ExampleField>
</Field>