序列化实现ICollection的类

时间:2016-09-20 08:46:56

标签: c# xml-serialization

我有一个实现ICollection<T>的集合类,其中包含一些用于完整性的自定义属性..

在这个简单的示例中,它是一个简单的请求/结果模式,请求本身作为结果类的属性传回。

[Serializable]
public class MyRequest
{
    public int SearchID { get; set; }
}

[Serializable]
public class MyResults : ICollection<MyElement>
{
    public MyRequest RequestDetails { get; set; }
    private ICollection<MyElement> _list = new List<MyElement>();

    /* ICollection interface methods removed */
}

[Serializable]
public class MyElement
{
    public int ID { get; set; }
}

这是用于实例化然后输出序列化字符串的示例程序。

class Program
{
    static void Main(string[] args)
    {
        MyResults m = new MyResults();
        m.RequestDetails = new MyRequest() { SearchID = 1 };

        for (int i = 1; i <= 5; i++)
        {
            m.Add(new MyElement { ID = i });
        }

        XmlDocument xmlDoc = new XmlDocument();
        XmlSerializer xmlSerializer = new XmlSerializer(m.GetType());
        using (MemoryStream xmlStream = new MemoryStream())
        {
            xmlSerializer.Serialize(xmlStream, m);
            xmlStream.Position = 0;
            xmlDoc.Load(xmlStream);
        }

        System.Diagnostics.Debug.WriteLine(xmlDoc.OuterXml);
    }
}

问题是输出不包括MyRequest详细信息......

<?xml version="1.0"?>
<ArrayOfMyElement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <MyElement>
        <ID>1</ID>
    </MyElement>
    <MyElement>
        <ID>2</ID>
    </MyElement>
    <MyElement>
        <ID>3</ID>
    </MyElement>
    <MyElement>
        <ID>4</ID>
    </MyElement>
    <MyElement>
        <ID>5</ID>
    </MyElement>
</ArrayOfMyElement>

2 个答案:

答案 0 :(得分:1)

XmlSerializer在序列化集合时总是忽略额外的属性;据我所知,唯一的方法就是不在ICollection<MyElement>类上实现MyResults,而是将集合公开为属性:

public class MyResults
{
    public MyRequest RequestDetails { get; set; }
    public ICollection<MyElement> Items { get; set; }
}

(XML序列化不需要Serializable属性)

答案 1 :(得分:0)

只需将 ICollection 更改为 Collection ,因为XmlSerialization不支持通用接口:

public class MyResults
{
    public MyResults()
    {
        this.Items= new Collection<MyElement>();
    }
    public MyRequest RequestDetails { get; set; }
    public Collection<MyElement> Items { get; set; }
}