是否允许从 [Serializable] 属性类过渡到 IXmlSerializable 类并返回?以下代码按预期进行序列化,但它不会反序列化 A 的第二个属性(它始终返回 null)。
谢谢!
using System.Xml.Serialization;
using System.IO;
using System;
namespace Serialization
{
[Serializable]
public class A
{
public B B
{
get;
set;
}
public string C
{
get;
set;
}
}
public class B : IXmlSerializable
{
private int _value;
public void SetValue(int value)
{
_value = value;
}
public int GetValue()
{
return _value;
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
int.TryParse(reader.ReadString(), out _value);
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteString(_value.ToString());
}
}
class Program
{
static void Main(string[] args)
{
A a = new A() {B = new B(), C = "bar"};
a.B.SetValue(1);
XmlSerializer serializer = new XmlSerializer(typeof(A));
Stream stream = File.Open("foo.xml", FileMode.Create);
serializer.Serialize(stream, a);
stream.Close();
stream = File.Open("foo.xml", FileMode.Open);
A a1 = serializer.Deserialize(stream) as A;
if (a1.B.GetValue() != 1 || a1.C != "bar")
{
System.Diagnostics.Trace.WriteLine("Failed.");
}
else
{
System.Diagnostics.Trace.WriteLine("Succeeded.");
}
}
}
}
产生预期的 XML:
<?xml version="1.0"?>
<A xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<B>1</B>
<C>bar</C>
</A>