2012-05-03 60 views
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。

回答

1

反序列化器不仅会反序列化属性值,还会包含它们的对象。该对象不能是IMyInterface类型,因为它是一个接口,不能实例化。您需要序列化该接口的实现,并将其反序列化,或者指定要反序列化的接口的默认实现。

+0

你能帮忙发布这个例子吗?我还没有完成。 –