0
我試圖序列化一個接口。我知道這是通過標準序列化不可能的,這就是爲什麼我在基類中使用自定義序列化的原因。如何使用IXmlSerializer序列化和反序列化接口?
public interface IFoo
{
object Value { get; }
}
public abstract class Foo<T> : IFoo, IXmlSerializable
{
[XmlElement]
public T Value { get; set; }
[XmlIgnore]
object IFoo.Value { get { return Value; } }
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader) { throw new NotImplementedException(); }
void IXmlSerializable.WriteXml(XmlWriter writer)
{
XmlSerializer serial = new XmlSerializer(Value.GetType());
serial.Serialize(writer, Value);
}
}
public class FooA : Foo<string> { }
public class FooB : Foo<int> { }
public class FooC : Foo<List<Double>> { }
public class FooContainer : List<IFoo>, IXmlSerializable
{
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader) { throw new NotImplementedException(); }
public void WriteXml(XmlWriter writer)
{
ForEach(x =>
{
XmlSerializer serial = new XmlSerializer(x.GetType());
serial.Serialize(writer, x);
});
}
}
class Program
{
static void Main(string[] args)
{
FooContainer fooList = new FooContainer()
{
new FooA() { Value = "String" },
new FooB() { Value = 2 },
new FooC() { Value = new List<double>() {2, 3.4 } }
};
XmlSerializer serializer = new XmlSerializer(fooList.GetType(),
new Type[] { typeof(FooA), typeof(FooB), typeof(FooC) });
System.IO.TextWriter textWriter = new System.IO.StreamWriter(@"C:\temp\demo.xml");
serializer.Serialize(textWriter, fooList);
textWriter.Close();
}
}
我的自定義序列化不正確。到目前爲止,所有的財產價值儲存,但反序列化我真的不知道如何做到這一點。
這個想法是保存屬性值並用元素恢復fooContainer。
你能幫忙發佈這個例子嗎?我還沒有完成。 –