使用DataContractSerializer

时间:2018-01-12 05:28:15

标签: c# .net serialization datacontractserializer

我们假设有以下通用集合:

public class MyCollection<T> : IEnumerable<T>
{
    IEnumerable<T> _items;

    public bool MySpecialProperty { get; set; }

    public MyCollection(IEnumerable<T> collection)
    {
        _items = collection;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _items.GetEnumerator();
    }
}

我尝试按DataContractSerializer使用

序列化此集合
MyCollection<int> original = new MyCollection<int>(new int[] { 1, 2, 3 }) 
{ 
    MySpecialProperty = false 
};
DataContractSerializer serializer = new DataContractSerializer(typeof(MyCollection<int>));
var builder = new StringBuilder();
using (XmlWriter writer = XmlTextWriter.Create(builder))
{
    serializer.WriteObject(writer, original);
}
var serialized = builder.ToString();

我知道,可以使用DataContractAttribute作为集合定义,使用DataMemberAttribute作为_itemsMySpecialProperty成员。但有没有办法将我的类序列化为普通集合?所以,我期待以下XML:

<MyCollection>  
    <Item>1</Item>  
    <Item>2</Item>  
    <Item>3</Item>
    <MySpecialProperty>false</MySpecialProperty>  
</MyCollection>

我曾尝试将CollectionDataContractAttribute用于集合定义,DataMemberAttribute用于MySpecialProperty,但它会在 System.Runtime.Serialization.dll中导致System.Runtime.Serialization.InvalidDataContractException异常。是否有其他方法可以获得上述XML结果?

0 个答案:

没有答案