开发者

Strongly Typed DataSet column requires custom type to implement IXmlSerializable?

I have a strongly typed Dataset with a single table with three columns. These columns all contain custom types.

DataColumn1 is of type Parent

DataColumn2 is of type Child1

DataColumn3 is of type Child2

Here is what these classes look like:

    [Serializable]
[XmlInclude(typeof(Child1)), XmlInclude(typeof(Child2))]
public abstract class Parent
{
    public int 开发者_开发技巧p1;
}
[Serializable]
public class Child1 :Parent
{
    public int c1;
}
[Serializable]
public class Child2 : Parent
{
    public int c1;
}

now, if I add a row with DataColumn1 being null, and DataColumns 2 and 3 populated and try to serialize it, it works:

            DataSet1 ds = new DataSet1();
        ds.DataTable1.AddDataTable1Row(null, new Child1(), new Child2());

        StringBuilder sb = new StringBuilder();
        using (StringWriter writer = new StringWriter(sb))
        {
            ds.WriteXml(writer);//Works!
        }

However, if I try to add a value to DataColumn1, it fails:

            DataSet1 ds = new DataSet1();
        ds.DataTable1.AddDataTable1Row(new Child1(), new Child1(), new Child2());

        StringBuilder sb = new StringBuilder();
        using (StringWriter writer = new StringWriter(sb))
        {
            ds.WriteXml(writer);//Fails!
        }

Here is the Exception:

"Type 'WindowsFormsApplication4.Child1, WindowsFormsApplication4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not implement IXmlSerializable interface therefore can not proceed with serialization."

I have also tried using the XmlSerializer to serialize the dataset, but I get the same exception.

Does anyone know of a way to get around this where I don't have to implement IXmlSerializable on all the Child classes? Alternatively, is there a way to implement IXmlSerializable keeping all default behavior the same (ie not having any class specific code in the ReadXml and WriteXml methods)


Try using a wrapper class around the parent in the first column like this

[Serializable]
public class Wrapper
{
    [XmlElement(ElementName="Child1", Type=typeof(Child1)),
    XmlElement(ElementName="Child2", Type=typeof(Child2))]
    public Parent Value { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜